vue非单文件组件的使用方法

标准化开发时的嵌套:

在实际开发中,通常会创建一个 APP 组件作为根组件,由这个根组件去管理其它的组件,而 Vue 实例只需要管理这个 APP 组件就行了。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>Vue2标准化开发时的嵌套</title>
		<script src="./js/vue.js"></script>
	</head>
	<body>

		<div id="APP"></div>

		<script>

			// 创建组件一
			const FrameHead = {
				template: `
					<div>
						<p>{
   
   {name}}</p>
					</div>
				`,
				data() {
					return {
						name:"组件一"
					}
				}
			}

			// 创建组件二
			const FrameBody = {
				template: `
					<div>
						<p>{
   
   {name}}</p>
					</div>
				`,
				data() {
					return {
						name:"组件二"
					}
				}
			}
			
			// 创建最大的根组件,由它来管理其它的组件
			const app = {
				template: `
					<div>
						<frame-head></frame-head>
						<frame-body></frame-body>
					</div>
				`,
				components:{
					FrameHead,
					FrameBody
				}
			}

			const vm = new Vue({
				template:`<app></app>`,
				el: "#APP",
				components: {app}
			});
		</script>
	</body>
</html>

 VueComponent 构造函数【扩展】:

<div id="APP">
	<my-code></my-code>
</div>
const MyCode = Vue.extend({
	template: `
		<div>
			<p>{
   
   {name}}</p>
		</div>
	`,
	data() {
		return {
			name:"你好呀!"
		}
	}
})

console.log(MyCode); // VueComponent

const vm = new Vue({
	el: "#APP",
	components: {
		MyCode
	}
});

:其实组件就是一个构造函数 VueComponent 。

 关于 VueComponent:

- 组件本质是一个名为 VueComponent 的构造函数,且不是程序员定义的,是 Vue.extend 自动生成的。
    
- 我们只要使用组件,Vue 解析时就会帮我们创建这个组件的实例对象,也就是 Vue 帮我们执行了 new VueComponent(options) 这个构造函数。
     
- 特别注意:每次调用 Vue.extend,返回的都是一个全新的 VueComponent 。

- 组件中的 this 指向:data 函数、methods 中的函数、watch 中的函数、computed 中的函数,它们的 this 均是【VueComponent 实例对象】。

- Vue 实例中的 this 指向:data 函数、methods 中的函数、watch 中的函数、computed 中的函数,它们的 this 均是【Vue 实例对象】。

 Vue 实例与 VueComponent 的内置关系:

// 查看 VueComponent 和 Vue 实例的关系
console.log( MyCode.prototype.__proto__ === Vue.prototype ); // true

 - 一个重要的内置关系:VueComponent.prototype.__proto__ === Vue.prototype

 为什么要有这个关系:让组件实例对象 VueComponent 可以访问到 Vue 原型上的属性和方   法。

 

 注:Vue 强制更改了 VueComponent 的原型对象指向 Object 的原型对象的隐式链,将其改到指向 Vue 的原型对象上。

原创作者:吴小糖

创作时间:2023.5.17

猜你喜欢

转载自blog.csdn.net/xiaowude_boke/article/details/130717660
今日推荐