一 vue的局部组件
局部组件格式
components: {
"子组件名称": {
template: "",
data: function() {
return {
str: "",
}
},
methods: {
run: function() {
alert(222)
}
}
},
},
例子1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<child></child>
<child></child>
<lisi></lisi>
</div>
<script src="../vue.js"></script>
<script>
Vue.component("zhangsan", {
template: "<h1>这是一个全局组件</h1>"
})
new Vue({ //父组件
el: "#app",
components: {
"child": { // child 是组件名称
template: "<h1 @click='run'>我是子组件--{{str}}</h1>",
data: function() {
return {
str: "哈哈哈",
}
},
methods: {
run: function() {
alert(222)
}
}
},
"lisi": {
template: "<h3>这是lisi</h3>"
}
},
data: {
},
methods: {
}
})
</script>
</body>
</html>
例子2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<child></child>
<child></child>
<lisi></lisi>
</div>
<!-- 第二种写法 -->
<template id="dv1">
<h1 @click='run'>我是子组件--{{str}}</h1>
</template>
<template id="dv2">
<h3>这是lisi</h3>
</template>
<script src="../vue.js"></script>
<script>
new Vue({ //父组件
el: "#app",
components: {
"child": { // child 是组件名称
template: "#dv1",
data: function() {
return {
str: "哈哈哈",
}
},
methods: {
run: function() {
alert(222)
}
}
},
"lisi": {
template: "#dv2"
}
},
data: {
},
methods: {
}
})
</script>
</body>
</html>