【问题标题】:Child component not update value from Parent子组件不更新父组件的值
【发布时间】:2020-02-14 03:38:22
【问题描述】:

我是新的 vue js。我不知道为什么当我更改父组件中的值时子组件中的值不会更新。谁能为我解释一下?我知道我可以使用Times Updated: {{ times}} 来显示。但我想把它分配给 count 做别的事情

父母 HTML

<div id="test">
  <button @click="clicktime">Click</button>
  <times-updated :times.sync="myData"></times-updated>
</div>

.js 文件

var vm = new Vue({
  el: '#test',
  data(){
    return {
      myData: 100
    }
  },

  methods: {
    clicktime() {
      vm.myData = Math.random();
    }
  }
})

孩子

Vue.component('times-updated', {
  props:["times"],
  data() {
    return {
      count: this.times
  }
},
  template: '<span>Times Updated: {{ count }}</span>',
});

链接codepen:enter link description here

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    在孩子中你可以直接使用你的道具值,然后它会起作用:

    Vue.component('times-updated', {
      props:["times"],
      data() {
        return {
          count: this.times // not needed, not reactive
      }
    },
      template: '<span>Times Updated: {{ this.times }}</span>',
    });
    

    【讨论】:

    • 如上所述因为我需要使用变量count来做其他事情所以我不想使用```{{this.times}}``来显示/感谢您的回复。
    • 啊,我明白了,如上所述,计算是要走的路。
    【解决方案2】:

    您需要computed 数据而不是数据元素,它可以保持监视和更新

    Vue.component('times-updated', {
      props:["times"],
      computed: {
        count: function(){
           return this.times;
        }
      },
      template: '<span>Times Updated: {{count}}</span>',
    });
    
    var vm = new Vue({
      el: '#test',
      data(){
        return {
          myData: 100
        }
      },
    
      methods: {
        clicktime() {
          vm.myData = Math.random();
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script>
    <div id="test">
      <button @click="clicktime">Click</button>
      <times-updated :times.sync="myData"></times-updated>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-18
      • 2018-07-15
      • 1970-01-01
      • 2023-02-20
      • 2019-07-28
      • 2022-01-13
      • 2019-08-27
      • 2018-11-18
      相关资源
      最近更新 更多