vue.js - 我如何在 Vue.js 中使用对象 Prop ?

标签 vue.js vue-component

vue.js 文档以这个为例:

props: ['initialCounter'],
data: function () {
  return { counter: this.initialCounter }
}

但是,initialCounter 在我的模板中有效,但 counter 无效。

我做错了什么?

完整代码如下:

<update-counter initialCounter="1" inline-template>
    <div>
        <div class="panel panel-default">
            <div class="panel-heading">My Counter @{{ initialCounter }}</div>

编辑:我缩小了问题范围。如果我像这样传递一个变量,它会起作用:

<update-partner :initial-counter="1" inline-template>

但是如果我传递一个对象,它就不起作用:

<update-partner :initial-counter="users" inline-template>

当我传递该对象时,initialCounter 在我的模板中起作用,但 counter 不起作用。

当我传递一个整数时,两个变量都有效。

传递对象时我需要做哪些不同的事情?

最佳答案

所以当您在组件中执行以下操作时会出现问题:

props: ['initialCounter'],
data: function () {
  return { counter: this.initialCounter }
}

您正在为 initialCounter 分配 counter 初始值,您稍后会在 mounted block 中更改该值。如果您需要更改值以在 counter 中设置,您必须在 initialCounter 上设置一个观察者,如下所示:

  watch:{
    initialCounter: function(newVal){
      this.counter = newVal;
    }
  }

你可以看到工作 fiddle .

关于vue.js - 我如何在 Vue.js 中使用对象 Prop ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41391111/

相关文章:

node.js - 如何在 laravel 5 中发布/使用 Node 模块?

javascript - 如果索引为 0,Vue.js 如何添加事件类

html - 如何在 Vuejs 中使用路由 View 作为选项卡?

javascript - 如何在 JS switch 语句中使用动态顺风类并在 Vue 中正确传递它们?

javascript - vue js 中组件加载时默认点击按钮

vue.js - NuxtJS路由错误: Page not found when navigating to an existing route

javascript - Vuejs - 如何将 Prop 从数据中的数组传递给子组件?

javascript - 未捕获类型错误 : Failed to execute 'drawImage' on Vue. js

javascript - Vue 输入传递一个数组

javascript - 如何在 Vue JS 的单个文件中访问样式内的组件变量