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

时间:2018-09-04 11:59:08

标签: vue.js sails.js

当SailsJS应用程序加载页面时,我让它从网址中提取id参数,并从数据库中加载配方。配方对象会正确记录到控制台,因此我确定它正在加载,但是没有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

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

2 个答案:

答案 0 :(得分:0)

答案是,当使用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]
    });

  }


};

答案 1 :(得分: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变量。 如果记录不存在,则需要一些处理程序。