一、main.js文件的基本内容
1. 引入vue
import Vue from 'vue';
2. 引入app.vue , 用他的内容替换index.html中的div id='app'的div
import App from '../app.vue';
3. 构建vue实例
new Vue({
el: '#app',// 渲染内容的目的地
render(creater){ //creater 是一个形参,可以是任何值
return creater(App);
}
});
//一般key值是固定的,参数是可变的
二、app.vue对应的内容
<template>
<div>
<pre>
* v-text
* v-html
* v-if
* v-show
* v-model
</pre>
<span v-text="text"></span>
<hr>
<div>
</template>
<script>
export default {
return {
data: {
text : "我是一个v-text"
}
}
}
</script>
<style></style>
v-text: 是innerText ,只能在双标签中使用
v-html:是innerHtml, 只能在双标签中使用,不能包含表达式
v-if: 元素是否移除或者是插入
v-show: 元素是否隐藏
v-model: 双向赋值, v-bind 是单向赋值 使用方法: v-bind: value = 'text'
v-bind: 单向赋值,支持参数表达式, 简写: 如: v-bind: value = 'text' 的简写就是 :value = 'text'
v-on: 给事件绑定对应的方法,或者直接写表达式。 简写@ , 如: v-on:click='change()' 的简写就是: @click="change()"
v-for: 可以是数组(entity, index) ,也可以是对象(value, key, index)
其中script代码为:
export default {
data() {
return {
name : '小王',
status: [{name: 'jack', age: 26},{name: 'rose', age: 30}]
}
},
methods:{
change(){
},
add: function(){
}
}
}
三、 当参数只有一个的时候,可以省略小括号, 当代码只有一行,并且只有返回值的时候,可以省略大括号如:
render: function(c){ return c(App);} 等价于: render: c => c(App)
四、 在<template></template>中使用变量或者函数不用加this, 在<script></script>中使用变量或者函数,必须加上this
五、 父子组件的使用, 父组件先通过import head from './components/head.vue' 引入子组件, 再在components中添加这些对象,就可以在<template>中使用了,直接写上<head></head> 就可以了,
如果想向子组件传值,则只需要父组件引用子组件的时候,在子组件上加上属性(属性的名称可以是任意值,这里以name为例),如:<head name='jack'></head>, 在只组件中,只需要在export default 中加上属性:props就可以了,props的值是数组,可以接受多个父组件的传值。 如: props: ['name'], 现在name这个变量就可以在子组件中进行使用了
六、全局组件的使用,首先需要在main.js中进行引入,再进行注册,代码如下: headVue就可以在所有的组件中进行使用了
import headVue from './headVue.vue';//引入组件
Vue.component("headVue", headVue); //注册组件
六、 组件中<style></style>中的样式,如果希望只在当前组件中有效,则需要加上scoped。 如: <style scoped></style>
七、 $emit和$on的使用,其中$on是监听和接收消息, $emit是发送消息。 下面是一个例子:
1. 新建一个连接器 connector.js。代码如下:
import Vue from 'vue'; //引入vue ,下面才能new Vue。 不然要报错
var connector = new Vue();
export default connector;
2. 父页面进行监听操作:使用$on, 代码如下:
<template>
<div>
<button @cilck="listener">监听接收消息</button>
</div>
</template>
<script>
import connetor from './connetor.js';
export default {
methods:{
listener(){
connetor.$on('phone', function(msg){
console.info(msg);
});
}
}
}
</script>
<style>
</style>
3. 子页面进行发送消息。使用:$emit, 代码如下:
<template>
<div>
<button @cilck="sendMsg">发送消息</button>
</div>
</template>
<script>
import connetor from './connetor.js';
export default {
methods:{
sendMsg(){
connetor.$emit('phone', '我给你发消息了,父页面。');
}
}
}
</script>
<style>
</style>
查看API文档的方式: