vue--day29--vue非单文件组件

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>非单文件组件</title>
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<div id="root">
<!--
Vue中使用组件的三大步
1、定义组件(创建组件)
2、注册组件
全局组件(component(‘组件名’,组件实例))
局部组件(components:{组件实例…})
3、使用组件(写组件标签)
<组件名></组件名> 双标签写法
<组件名/> 单标签写法


1.如何定义一个组件?
使用Vue.extend(options)创建,其中options和new Vue(options)时传入的那个options几乎一样,但也有点区别;
区别如下:
(1)el不要写,为什么?
最终所有的组件都要经过一个vm的管理,由vm中的el决定服务哪个容器。备注:使用template可以配置组件结构。

(2)data必须写成函数,为什么?
避免组件被复用时,数据存在引用关系,
备注:使用template 可以配置组件结构
比如我父组件要多次复用一个子组件,那如果其中一个子组件做了修改数据操作,其他复用的地方数据也会被修改。看看下面的代码,就明白了
// 举例说明
// let data={
// a:1,
// b:2
// }
// const x1=data;
// const x2=data;
// x1.a=99;
// console.log(x2.a);// 其中也是99

//换种写法 函数式子
// function data(){
// return {
// a:1,
// b:2
// }
// }

// const x1=data();
// const x2=data();
// x1.a=99;
// console.log(x1.a);// 是1
如何注册一个组件
全局组件 靠Vue.component('组件名',组件)
局部组件 靠new Vue 的时候传入components 选项
便携组件标签
<school></school>

-->
<!--第三步编写组件标签-->
<hello></hello>
<school></school>
<hr />
<student></student>
</div>
<hr />
<hr />
<div id="root2">
<hello></hello>
</div>
</body>

<script type="text/javascript">
// 创建school 组件 // 组件中的data 一定要写成函数式

// 举例说明
// let data={
// a:1,
// b:2
// }
// const x1=data;
// const x2=data;
// x1.a=99;
// console.log(x2.a);// 其中也是99

//换种写法 函数式子
// function data(){
// return {
// a:1,
// b:2
// }
// }

// const x1=data();
// const x2=data();
// x1.a=99;
// console.log(x1.a);// 是1

//创建组件
const school = Vue.extend({
template: `
<div>
<h2>学校名称{{schoolName}}</h2>
<h2>学校地址{{address}}</h2>
</div>
`,

data() {
return {
schoolName: "洛阳理工",
address: "河南",
};
},
});

//创建组件
const student = Vue.extend({
template: `
<div>

<h2>学生姓名{{studentName}}</h2>
<h2>学生年龄{{age}}</h2>
</div>
`,
data() {
return {
studentName: "你好",
age: 20,
};
},
});

const hello = Vue.extend({
template: `
<div>

<h2>你好呀{{name}}</h2>

</div>
`,
data() {
return {
name: "smy",
};
},
});

//第二步全局注册组件
Vue.component("hello", hello);

new Vue({
el: "#root",
// 第二步 注册 局部注册
components: {
school,
student,
},

methods: {
stop() {
//clearInterval(this.timer);
this.$destroy();
},
},
});

new Vue({
el: "#root2",
// 第二步 注册 局部注册
components: {
hello,
},
});
</script>
</html>
posted @ 2023-07-19 00:29  雪落无痕1  阅读(16)  评论(0)    收藏  举报