Vue 组件化编程
非单文件组件
定义组件
使用
Vue.extend(options)创建
不要写el
data要写成函数,避免组件被复用时,数据存在引用关系
注册组件
- 局部注册:new Vue()的时候,options传入components
- 全局注册:Vue.Component("组件名",组件)
全局注册
<div id="app"><!-- 使用组件 --><school></school><!-- 单标签写法需要在脚手架坏境下使用 --><!-- <school /> --></div>
Vue.config.productionTip = false;// 定义组件const school = Vue.extend({template: `<div><h1>我是一个school组件</h1><h1>我是:{{userName}}</h1><h1>我是:{{func()}}</h1></div>`,data() {return {userName: "张三"}},methods: {func() {return 100;}}})// 全局注册组件Vue.component("school", school);var vm = new Vue({el: "#app",data() {return {}},})
局部注册
<div id="app"><!-- 使用组件 --><school></school><!-- 单标签写法需要在脚手架坏境下使用 --><!-- <school /> --></div>
Vue.config.productionTip = false;// 定义组件const school = Vue.extend({template: `<div><h1>我是一个school组件</h1><h1>我是:{{userName}}</h1><h1>我是:{{func()}}</h1></div>`,data() {return {userName: "张三"}},methods: {func() {return 100;}}})// 全局注册组件// Vue.component("school", school);var vm = new Vue({el: "#app",data() {return {}},// 局部注册组件components:{school;})
组件嵌套
<div id="app"></div>
 Vue.config.productionTip = false;//定义student组件const student = Vue.extend({name: 'student',template: `<div><h4>学生姓名:{{name}}</h4>	<h4>学生年龄:{{age}}</h4>	</div>`,data() { return { name: '张三', age: 18 } }})//定义school组件const school = Vue.extend({name: 'school',template: `<div><h3>学校名称:{{name}}</h3>	<h3>学校地址:{{address}}</h3>	<student></student></div>`,data() { return { name: '某某大学', address: '北京' } },//注册组件(局部)components: { student }})//定义hello组件const hello = Vue.extend({template: `<h3>{{msg}}</h3>`,data() { return { msg: '欢迎来到某某大学学习!' } }})//定义app组件const app = Vue.extend({template: `<div>	<hello></hello><school></school></div>`,components: { school, hello }})//创建vmnew Vue({el: '#app',template: '<app></app>',//注册组件(局部)components: { app }})

- Vue.extend()方法本质就是实例化VueComponent构造函数
- 两种注册方法的区别:
 全局注册:只需要注册一次,在任何组件中都可以使用
 局部注册:在变量A中注册,只能在A中使用组件
- VueComponent.prototype.__proto__===Vue.prototype
组件命名特性:
- 可以使用小写或者大写,首字母都会自动转为大写
- my-school和- myschool都为转为同样格式的- MySchool,但是myschool需要在- 脚手架坏境下使用
- 使用的组件名可以不和组件定义的名字相同,组件名可以自定义
- 使用的组件名需要规避HTML中已有的元素标签名称
单文件组件
MySchool.vue
<template><h1>我是MySchool组件</h1>
</template><script>
export default {name:"MySchool",  // 不能使用单个单词,如schooldata(){return{msg:"欢迎学习vue",}}
}
</script><style></style>
MyStudent.vue
<template><h1>我是MyStudent.组件</h1>
</template><script>
export default {name:"MyStudent.",  // 不能使用单个单词,如school
}
</script><style></style>
MyApp.vue
<template><div id="app"><MySchool></MySchool><MyStudent></MyStudent></div>
</template><script>
// 导入
import MySchool from './MySchool.vue';
import MyStudent from './MyStudent.vue';
export default {name:"MyApp.",  // 不能使用单个单词,如school// 注册components:{MySchool,MyStudent}
}
</script><style></style>

- 失联
最后编辑时间 2024,3,31;16:32