vue.js - 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;
});
当父母的道具发生变化时,这是重新渲染孩子的唯一方法吗?
解决方案
它应该如以下示例所示工作:
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>
推荐阅读
- flutter - 由于 EGL_BAD_ALLOC(错误 3003 (EGL_BAD_ALLOC))在 webrtc 中渲染时无法创建 EGL 上下文
- docker - 是否可以基于 SCRATCH 参考构建 nodeJS 容器?
- docassemble - 在 docassemble 中编写辅助函数/代码/采访,直接到数据目录(即绕过操场)?
- python - Flask restful/sqlalchemy update/setattr 多个dict同时
- python - Jupyter 无法识别刚刚安装的模块 pip
- c# - APReleaseProcess_Extension 自定义代码在 Acumatica ERP 版本 2017 R2 中不起作用
- reactjs - 材质 UI 网格间距属性不起作用
- xampp - 如何通过 xampp 运行联系表单
- html - 如何在 Wordpress HTML5 视频中禁用画中画模式
- python - Python - 如何使用 .click/selenium 打印 URL