Vue.js--组件高级用法--递归组件、内联模板
递归组件组件在它的模板内可以递归调用自己,只要给组件设置name的选项就可以了。<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-s...
·
递归组件
组件在它的模板内可以递归调用自己,只要给组件设置name的选项就可以了。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<title>递归组件</title>
</head>
<body>
<div id="app">
<child-component :count="1"></child-component>
</div>
<script>
Vue.component('child-component',{
name: 'child-component',
props: {
count: {
type: Number,
default: 1
}
},
template: '\
<div class="child">\
<child-component :count="count + 1" v-if="count < 3" ></child-component>\
</div>'
});
var app = new Vue({
el: '#app'
});
</script>
</body>
</html>
设置了name后,在组件模板内就可以递归使用了,不过需要注意的是,**必须给一个条件来限制递归数量,否则会抛出错误:max stack size exceeded。
内联模板
组件的模板一般都是在template选项内定义的,Vue提供了一个内联模板的功能,在使用组件时,给组件标签使用inline-template特性,组件就会把它的内容当作模板,而不是把它当内容分发,这让模板更灵活。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<title>内联模板</title>
</head>
<body>
<div id="app">
<child-component inline-template>
<div>
<h2>在父组件中定义组件的模板
<p>{{message}}</p>
<p>{{msg}}</p>
</h2>
</div>
</child-component>
</div>
<script>
Vue.component('child-component',{
data: function () {
return {
msg: '在子组件声明的数据'
}
}
});
var app = new Vue({
el: '#app',
data: {
message: '在父组件中声明的数据'
}
});
</script>
</body>
</html>
渲染结果为:
<div id="app">
<div>
<h2>在父组件中定义子组件的模板</h2>
<p>在父组件中声明的数据</p>
<p>在子组件中声明的数据</p>
</div>
</div>
在父组件中声明的数据message和子组件中声明的数据msg,两个都可以渲染(如果同名,优先使用子组件的数据)。这反而是内联模板的缺点,就是作用域比较难理解,如果不是非常特殊的场景,建议不要轻易使用内联模板。
更多推荐
已为社区贡献6条内容
所有评论(0)