前端框架vue.js系列(8):嵌套元素、导入外部文件作为模板

来源:互联网 发布:网络推广顾问是什么 编辑:程序博客网 时间:2024/06/05 02:19

组件嵌套元素

一般定义组件,组件内不会再嵌套其他元素标签,因为即使嵌套上去也不会生效。如下所示:

<my-component :item="item"><p>我是嵌套标签</p></my-component>
此时<p>标签并不会渲染出来。

当然,正常情况下也不会有这种需求,因为如果你需要显示<p>标签,只要写入到<my-component>组件内即可。那有个疑问就是既然可以往组件内传参,那可不可以往组件内传递元素标签呢?这就意味着子组件的元素标签结构由父组件来决定。答案是可以的,这就是组件嵌套元素。

组件嵌套元素,即在子组件中使用<slot>标签用于替换父组件传入的元素标签。Demo如下:

<body><div id="app"><!-- slot为子组件的嵌套位置 --><my-component :item="item"><p slot="slot1">我是嵌套标签,位置位于模板的slot元素下</p></my-component></div></body><script type="text/x-template" id="pid"><div><label>{{item}}</label><slot name="slot1">(我是slot1,只有在没有要分发的内容时才会显示这句话)</slot><slot name="slot2">(我是slot2,只有在没有要分发的内容时才会显示这句话)</slot></div></script><script>Vue.component("my-component", {props: ["item"], //第三方传参template: '#pid',data: function() {return {}}});var vue = new Vue({el: "#app",data: {item: "slot嵌套标签测试:"}});</script>
运行结果:


导入.html文件作为模板

正常情况下,定义模板都使用<script type="text/x-template" id="pid"></script>来定义,简单一点的也可直接通过文本写到template中。但是这都有一定的局限性,如果不同页面,以上的模板定义方法均不可以实现模板共享。此时,需要将模板写到一个独立的文件中,通过导入实现模板共享。

我们新建一个com.html文件,这个文件作为模板,代码如下:

<p>我是导入模板    自身参数:{{a}}|外部入参:{{b}}</p>
导入com.html我们需要借助jquery.js,代码如下:
<html><head><meta charset="utf-8" /><title></title><script type="text/javascript" src="../js/libs/vue/2.4.2/vue.js"></script><script type="text/javascript" src="../js/libs/jquery/jquery-1.11.3.js"></script></head><body><div id="app"><hello-world :b="parame"></hello-world></div></body><script>Vue.component('hello-world', function(resolve, reject) {$.get("./../xtemplate/com.html").then(function(res) {resolve({template: res,props: ["b"],data: function() {return {a: "a"}}})});});var vue = new Vue({el: "#app",data: {parame: "b"},methods: {},filters: {},computed: {},components: {},watch: {}});</script></html>
运行结果:

阅读全文
1 0
原创粉丝点击