代码理解:
HTML buf
<!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">
<title>helloVueTemplate模板</title>
<script type="text/javascript" src="../assets/js/vue.js"></script>
</head>
<body>
<!-- 自定义组件 -->
<div id="app">
<p v-text="message"></p>
<!-- component 必须放在#app(Vue作用域里)里面 -->
<globalcomp></globalcomp>
<!-- 局部组件(自定义标签)直接使用 -->
<foo vue-abc="Vue-ABC"></foo>
<!-- component :is 显示data指定名称的组件 :abc还可以绑定data数据 -->
<component :is="currentComponent" :abc="message"></component>
<!-- 外部引用 -->
<baz></baz>
<button @click="switchComponent">switch</button>
</div>
<hr>
<template id="innerTemplate">
<h2 style="color: red;">This Is A innerTemplate Test.</h2>
</template>
</body>
</html>
JavaScript buf
<script type="x-template" id="scriptTemplate">
<h2 style="color: red;">This Is A scriptTemplate Test.</h2>
</script>
<script type="text/javascript">
// 全局Vue.component()方法 可对多个生效Vue对象(全局) 组件就是制作自定义的 标签 (配合模板使用)
Vue.component('globalcomp',{
template: ` <h2 style="color: green;">This Is A globalComponent Test.</h2> `,
});
var sonComponent = {
'son1': {
template: ` <h2 style="color: red;">This Is A sonComponent son1.</h2> `,
},
'son2': {
template: ` <h2 style="color: red;">This Is A sonComponent son2.</h2> `,
}
};
//外部组件 在Vue对象中引用 一般写在上面 按照js加载顺序
var outterComponent = {
//且子组件标签必须写在一个根元素里 eg:div 也就是说模板就只加载一个Element
template: `<div>
<h2 style="color: green;">This Is A outerLocalComponent baz.</h2>
<son2></son2>
</div>`,
//引用子组件声明 +s
components: sonComponent,
};
var app = new Vue({
el:'#app',
data: {
message: 'Template模板 切换',
currentComponent: 'bar',
},
// Template的三种写法 全部替换到Vue绑定的app标签上 新增``表示字符串使用
// 模板直接写在app里面
// 模板写在HTML的template元素里 用选择符绑定 常用#ID
// 模板写在<script type="x-template">里 可以引用外部模板文件 src
// template:`
// <h2 style="color: red;">This Is A Template Test.</h2>
// `,
// template: `#innerTemplate`,
// template: `#scriptTemplate`,
//局部组件 只在该Vue域里有效
components: {
"foo": {
template: `<div>
<h2 style="color: green;">This Is A localComponent foo.{{vueAbc}}</h2>
<son1></son1>
</div>`,
// props 选项必须是数组形式的属性名称 可以用来获取替代标签的属性
// 遇到- 需要小驼峰写法Js 该属性的值直接作类似data数据使用
props: ['vueAbc'],
components: sonComponent,
},
'bar': {
template: `<h2 style="color: green;">This Is A localComponent bar.{{abc}}</h2>`,
//'abc'这里绑定了data中的数据 从而渲染数据
props: ['abc'],
},
//外部引用组件模板 避免构造器过长拖拉 影响可读性
'baz': outterComponent,
'swt': {
template: `<h2>切换处!</h2>`,
},
},
methods: {
//不能ES6语法()=>{} 表示 ?
// switchComponent: function () {
// this.currentComponent = (this.currentComponent ==='bar'? 'swt' : 'bar');
// },
switchComponent (){
this.currentComponent = (this.currentComponent ==='bar'? 'swt' : 'bar');
},
},
});
</script>
对应指令测试展示效果:
Over~