全局自定义指令
Vue.directive('red',function(el){
el.style.background='red'
})
<p v-red>aaaap>
自定义指令传参
<html>
<head>
<meta charset="utf-8" />
<title>title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js">script>
head>
<body>
<div id="app">
<p v-bgcolor='color'>aaap>
<p v-bgcolor="'green'">bbbp>
div>
<script type="text/javascript">
Vue.directive('bgcolor',function(el,binding){ //binding为传进来的第一个参数
el.style.background=binding.value //binding.value是传递进来的第一个参数值
})
let vm=new Vue({
el:"#app",
data:{
color:'red',
}
})
script>
body>
html>
定义好一个组件之后,可以反复调用
<html lang="en">
<head>
<meta charset="UTF-8">
<title>VUEtitle>
<script src="bower_components/vue/dist/vue.js">script>
<style>
style>
head>
<body>
<div id="box">
<aaa>aaa>
<aaa>aaa>
<aaa>aaa>
div>
<script>
var Aaa=Vue.extend({
template:'我是全局组件
' //定义模板
});
Vue.component('aaa',Aaa); //注册组件
var vm=new Vue({
el:'#box',
});
script>
body>
html>
<html>
<head>
<meta charset="utf-8">
<title>title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js">script>
head>
<body>
<div id="app">
<div v-if="msg=='login'">
<aaa>aaa>
div>
<div v-else-if="msg=='register'">
<bbb>bbb>
div>
<div v-else >
<ccc>ccc>
div>
<div id="butgroup">
<button type="button" @click="goto('login')">去登陆button>
<button type="button" @click="goto('register')">去注册button>
<button type="button" @click="goto('other')">哪也不去button>
div>
div>
<template id="temp1">
<form action="#" method="get">br>
用户名:<input type="text" />br>
密码:<input type="password" />br>
<input type="submit" value="登录" />
form>
template>
<template id="temp2">
<form action="#" method="get">
用户名:<input type="text" />br>
密码:<input type="password" />br>
邮箱:<input type="text"/>br>
电话:<input type="tel" />br>
<input type="submit" value="注册" />
form>
template>
<template id="temp3">
<label>待完善页面label>
template>
<script type="text/javascript">
Vue.component("aaa",{ //注册组件 通过template标签的id引用template标签进行注册
template:'#temp1'
})
Vue.component("bbb",{
template:'#temp2'
})
Vue.component("ccc",{
template:'#temp3'
})
let vm=new Vue({
el:"#app",
data:{
msg:'login'
},
methods:{
goto:function(msg){
this.msg=msg
}
}
})
script>
body>
html>
在template模板当中,想要使用data,需要在其对应的component中定义 (定义一个data方法,将需要的值作为返回值)
<template id="temp1">
<form action="#" method="get">br>
{{osname}} {{osauthor}}
用户名:<input type="text" />br>
密码:<input type="password" />br>
<input type="submit" value="登录" />
form>
template>
<script>
Vue.component("aaa",{
template:'#temp1',
data:function(){
return{
osname:'无敌os',
osauthor:'tom'
}
}
})
script>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vuetitle>
<script src="bower_components/vue/dist/vue.js">script>
<style>
style>
head>
<body>
<div id="box">
<my-aaa>my-aaa>
div>
<script>
var vm=new Vue({
el:'#box',
components:{
'my-aaa':{
data(){
return {
msg:'welcome vue'
}
},
methods:{
change(){
this.msg='changed';
}
},
template:'局部组件-->{{msg}}
'
}
}
});
script>
body>
html>