在 Sails 应用程序中加载后访问 Vue 中的对象属性

Accessing object properties in Vue after loading in Sails app

当 SailsJS 应用程序加载页面时,我让它从 url 中提取 id 参数并从数据库中加载食谱。配方对象正确地记录到控制台,所以我确定它正在加载,但是 none 的 Vue 变量正在呈现。

我正在加载此控制器操作中的数据:

// api/controllers/recipes/view-single-recipe.js

module.exports = {


  friendlyName: 'View single recipe',


  description: 'Display "Single recipe" page.',


  exits: {

    success: {
      viewTemplatePath: 'pages/recipes/single-recipe'
    }

  },


  fn: async function (inputs, exits) {
    const recipe =  await Recipe.find({id: this.req.params.id}).populate('ingredients')
    console.log(recipe) //logs the data correctly
    return exits.success({
      recipe: recipe
    });

  }


};

然后我尝试使用 VueJS 在我的视图中访问 recipe 对象:

<!-- views/pages/recipes/single-recipe.ejs -->

<div id="single-recipe" v-cloak>

  <h1>{{recipe.name}}</h1> <!-- rendering as <h1></h1>
  
  <!-- ... more stuff ... -->
 
</div>


<%- /* Expose server-rendered data as window.SAILS_LOCALS :: */ exposeLocalsToBrowser() %>

这是加载的数据对象:

[{
  ingredients: [
    [Object],
    [Object],
    [Object],
    [Object],
    [Object]
  ],
  createdAt: 1536016866419,
  updatedAt: 1536016866419,
  id: '5b8c169936f1df3439fa39c7',
  name: 'Sweet Green',
  ratingSweet: 2,
  ratingTexture: 5,
  ratingOverall: 4,
  ratingColor: 5,
  notes: 'Personal favorite, maybe needs more ginger',
  owner: '5b8c16301cee97343513e184'
}]

不确定这是否重要,但这是路线: 'GET /recipes/single-recipe/:id': { action: 'recipes/view-single-recipe' }

正在访问的 URL 是 http://localhost:1337/recipes/single-recipe/5b8c169936f1df3439fa39c7

如何访问视图中的数据对象属性?

答案是使用find()查询时,返回的结果是一个数组。所以如果只有一个结果,需要在数组[0]

的第一个结果处访问

// api/controllers/recipes/view-single-recipe.js

module.exports = {

// ...

  fn: async function (inputs, exits) {
    const recipe =  await Recipe.find({id: this.req.params.id}).populate('ingredients')
    console.log(recipe) //logs the data correctly
    return exits.success({
      recipe: recipe[0]
    });

  }


};

你应该使用findOne

// api/controllers/recipes/view-single-recipe.js

module.exports = {
  friendlyName: 'View single recipe',
  description: 'Display "Single recipe" page.',
  exits: {
    success: {
      viewTemplatePath: 'pages/recipes/single-recipe'
    }
  },

  fn: async function (inputs, exits) {
    const recipe = await Recipe.findOne({
      id: this.req.params.id
    }).populate('ingredients')

    return exits.success({ recipe: recipe });
  }
};

另请注意,未使用 fn 中的 inputs 变量。 如果记录不存在,则需要一些处理程序。