首页 > 解决方案 > Vue 3 道具属性未更新

问题描述

我有如下父组件:

<template>
  <button @click="initStr" value="init str" />
  <child :str="str" />
</template>
<script>
export default {
  components: { child, },
  setup() {
    const str= ref("");
    function initStr() {
      str.value = "init";
    }

    return {
      str,
      initStr,
    };
  }
};
</script>

问题是当单击父组件上的按钮以初始化字符串时,子组件不会使用新字符串重新呈现。我必须在子组件中创建另一个 ref 变量,然后观察道具来分配新的字符串,如下所示:

const string = ref(props.str);
watch(props, props => {
  string.value = props.str;
});

当父母的道具发生变化时,这是重新渲染孩子的唯一方法吗?

标签: vue.js

解决方案


它应该如以下示例所示工作:

const {
  createApp
} = Vue;
const App = {

  setup() {
    const str = Vue.ref("");

    function initStr() {
      str.value = "init";
    }

    return {
      str,
      initStr,
    };
  }
}
const app = createApp(App)
app.component('child', {
  props: ['str'],
  template: `
<div> str : {{str}}</div>
`
})

app.mount('#app')
<script src="https://unpkg.com/vue@3.0.0-rc.11/dist/vue.global.prod.js"></script>

<div id="app">
  <button @click="initStr">
   init str
  </button>
  <child :str="str" />
</div>


推荐阅读