7.5.2 内联模板演示代码
Opened this issue · 1 comments
netuxi commented
7.5.2 内联模板演示代码中子组件无法解析父组件中的 message 数据。以下是我的代码。
<!DOCTYPE html>
<html lang="zh-Hans">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>内联模板</title>
<script src="./../../lib/vue.js"></script>
</head>
<body>
<div id="app">
<child-component inline-template>
<div>
<h2>在父组件中定义子组件的模板</h2>
<p>{{ message }}</p>
<p>{{ msg }}</p>
</div>
</child-component>
</div>
<script>
Vue.component("child-component", {
data: function () {
return {
msg: "在子组件声明的数据"
}
}
});
var app = new Vue({
el: "#app",
data: {
message: "在父组件声明的数据"
}
});
</script>
</body>
</html>
下面是控制台打印的错误。
Property or method "message" is not defined on the instance but referenced during render.
Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.
当我删除了 <p>{{ message }}</p>
之后,就没有了错误。我是 Vue 的初学者,我无法确定是否是书上的代码出了问题。对了,我的 Vue 版本为 2.6.11。 @icarusion
Envythink commented
你的代码没有错误,这样肯定会报错,因为message是在父组件内定义的,你现在直接用在子组件内肯定不行,除非在子组件内使用props的数组写法来进行接收,并在child-component组件内使用:message=message来进行传递就可以了。
<div id="app">
<child-component inline-template :message="message">
<div>
<p>在父组件中定义子组件的模板</p>
<p>{{ message }}</p>
<p>{{ msg }}</p>
</div>
</child-component>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="text/javascript">
Vue.component('child-component',{
props:['message'],
data: function () {
return {
msg: "在子组件中声明的数据"
}
}
});
var app = new Vue({
el:"#app",
data: {
message: "在父组件中声明的数据"
}
})
</script>