Vue内敛模板

在学习《Vue实战》一书时,学习到组件高级应用-内联模板这一小节时,照着书上的例子敲了一遍,发现未达到预期,切报错。

书上源代码如下:

 1 <!DOCTYPE html> 
 2 <html> 
 3 <head> 
 4     <meta charset=” utf-8” > 
 5     <title>内联模板</title>
 6     <script src="../../vue.js" type="text/javascript"></script>
 7 </head> 
 8 <body>
 9     <div id="app" v-cloak>
10         Vue提供一个内联模板的功能,在使用组件时,给组件标签使用inline-template特性,组件就会把它的内容当作模板,而不是把它当作内容分发。
11         <child-component inline-template>
12             <div>
13                 <h2>在父组件中定义子组件的模板</h2>
14                 <p>{{message}}</p>
15                 <p>{{msg}}</p>
16             </div>
17         </child-component>
18     </div>    
19 <script>
20     Vue.component('child-component',{
21         data:function(){
22             return {
23                 msg:'在子组件声明的数据'
24             }
25         }
26     });    
27     var app=new Vue({
28         el:'#app',
29         data:{
30             message:'在父组件中声明的数据'
31         }
32     })
33 </script> 
34 </body> 
35 </html>

 

实现效果及错误如下:

 

 

 经查询:inline-template没有那么强大,组件之间的通信仍然需要使用props,修改如下代码即可实现。

 1 <!DOCTYPE html> 
 2 <html> 
 3 <head> 
 4     <meta charset=” utf-8” > 
 5     <title>内联模板</title>
 6     <script src="../../vue.js" type="text/javascript"></script>
 7 </head> 
 8 <body>
 9     <div id="app" v-cloak>
10         Vue提供一个内联模板的功能,在使用组件时,给组件标签使用inline-template特性,组件就会把它的内容当作模板,而不是把它当作内容分发。
11         <child-component inline-template  :message="message">
12             <div>
13                 <h2>在父组件中定义子组件的模板</h2>
14                 <p>{{message}}</p>
15                 <p>{{msg}}</p>
16             </div>
17         </child-component>
18     </div>    
19 <script>
20     Vue.component('child-component',{
21         props:['message'],
22         data:function(){
23             return {
24                 msg:'在子组件声明的数据'
25             }
26         }
27     });    
28     var app=new Vue({
29         el:'#app',
30         data:{
31             message:'在父组件中声明的数据'
32         }
33     })
34 </script> 
35 </body> 
36 </html>

 

posted @ 2019-10-12 16:34  用脑袋行走的人  阅读(397)  评论(0编辑  收藏  举报