快速上手写一个组件
<div id="app">
<test-component></test-component>
</div>
<script type="text/javascript">
Vue.component("test-component", {
data: function(){
return {
count: 0
}
},
template:'<div><button type="button" @click="clickMe">clock me times:{{count}}</button></div>',
methods: {
clickMe: function(){
this.count++;
}
}
});
var vm = new Vue({
el: "#app",
data: {}
});
</script>
组件的data
组件的data为什么指向的是一个匿名函数,因为new Vue()是一个实例
实例在js中是引用类型,而组件要被复用,要保证组件的独一无二、互不干扰
组件属性、回调、插槽
用户自定义属性,见 title="title1"
用户自定义事件,见 @beclicked="beclicked1"
用户自定义内容,见 <slot></slot>
,如果只有一个插槽,可以省略slot的name
<template v-slot:test1>
<span>slot的内容这里</span>
</template>
作用域插槽,本质上是一个返回组件的函数
<template v-slot:test1="{value}">
<span v-if="value > 0.5">内容>0.5</span>
<span v-if="value <= 0.5">内容<=0.5</span>
</template>
没有在props中声明的属性,会被挂载到组件template的根节点上,见 not-declare
<div id="app">
<test-component title="title1" @beclicked="beclicked1" not-declare="xxx">
<span slot="test1">slot的内容这里</span>
</test-component>
</div>
<script type="text/javascript">
Vue.component("test-component", {
props : ["title"],
data: function(){
return {
count: 0,
value: Math.random()
}
},
template:'<div><button type="button" @click="clickme">I am {{title}} clock me times:{{count}}</button><slot name="test1" :value="value"></slot></div>',
methods: {
clickme: function(){
this.count++;
this.$emit("beclicked", this.title, this.count);
}
}
});
var vm = new Vue({
el: "#app",
methods: {
beclicked1: function(title, count) {
alert(title + "组件被点击了" + count + "次数");
}
}
});
</script>
局部注册
<script type="text/javascript">
var vm = new Vue({
el: "#app",
data: {},
components: {
"test-component" : {
template:'<div>test-component组件</div>'
}
}
});
</script>
单文件注册
需要安装 npm
# 之前有装过,npm自更新
npm install npm@latest -g
# 清理npm缓存
npm cache clean -f
# 安装版本管理工具 n
npm install -g n
# 更新node
n stable
由于网络原因 安装 cnpm
npm install -g cnpm --registry=https://registry.npm.taobao.org
安装 vue-cli
cnpm install -g @vue/cli
安装 webpack
webpack
是 JavaScript
打包器(module bundler)
cnpm install -g webpack
查看 vue
版本
vue --version
创建一个 vue
项目
vue create vue-demo
单文件组件
<template>
<div class="red" @click="test">单文件组件 {{msg}}</div>
</template>
<script>
export default {
name: "Single",
props: {
msg: {
type: String,
default: "test single file"
},
},
data() {
return {
}
},
methods:{
test: function() {
alert("test");
}
}
}
</script>
<style>
.red {
color: red;
}
</style>
css组件化,只在当前组件内生效
<style scoped>
.red {
color: red;
}
</style>
导入单文件组件
import Single from "./components/Single.vue"
export default {
name: 'xxx',
components: {
Single
}
}
全局注册单文件组件,在入口文件处,即:new Vue()前面注册就行了
import Single from "./components/Single.vue"
Vue.component('Single', Single)