首页 > 解决方案 > 如何将 v-bind 的值更新为 prop?

问题描述

这是我将数据“时间”和“breedKey”传递给孩子的父页面

<template>
        <MyChildComponent v-bind:breedKey="breedKey" v-bind:time="time"> </MyChildComponent>
</template>

<script>
        data() {
                return {
                  time:[]
                  breedKey:[]
                }
            },
<script>

这是我成功获取值的子页面,但是当父值更改时,值没有更新。

props: ["breedKey", "time"],

data() {
        return {
          thedate: this.time,
          topic: this.breedKey
        }

标签: javascriptvue.jsdata-bindingprop

解决方案


data仅使用 props 值初始化。

如果你想有反应,你可以直接引用道具。

Vue.config.devtools = false;
Vue.config.productionTip = false;

const MyChildComponent = Vue.component('mychildcomponent', {
  template: '#mychildcomponent',
  props: ["breedKey", "time"]
})

var app = new Vue({
  el: '#app',
  components: {
    MyChildComponent
  },
  data() {
    return {
      time : [],
      breedKey: []
    }
  },
  methods: {
    addTime() {
      this.time.push(Math.floor(Math.random() * 100));
    },
    addKey() {
      this.breedKey.push(Math.floor(Math.random() * 100));
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/vuex@3.1.2/dist/vuex.js"></script>

<div id="app">
  <div>
    <button @click="addTime">Add time</button>
    <button @click="addKey">Add key</button>
    <mychildcomponent v-bind:breed-key="breedKey" v-bind:time="time" />
  </div>
</div>

<div>

  <div style="display:none">
    <div id="mychildcomponent">
      <div>
        time : {{ time }}
        breedKey : {{ breedKey }}
      </div>
    </div>
  </div>


推荐阅读