1.如何在不搭建脚手架的情况下,写一个vue后缀的文件,然后浏览呢?
- 先安装一个全局的快速原型开发的功能
npm install -g @vue/cli-service-global
- 然后在需要浏览的文件中
在终端中打开
,输入vue serve
2.父子组件的传值
a.父传子 关键字: props
- 子组件定义
props
属性props:['num','age'.....]
- 父组件使用子组件时 先导入
import son from './son.vue'
,然后注册主键components:{ son }
,最后挂载,以标签形式<son></son>
具体代码:
父组件:
<template>
<div>
<h1>我是父组件</h1>
<son msg="123"></son>
</div>
</template>
<script>
import son from './son.vue'
export default {
components:{
son
},
}
</script>
子组件:
<template>
<div>
<h2>我是子组件</h2>
<p>父组件传过来的值: {{msg}}</p>
</div>
</template>
<script>
export default {
props:['msg'],
}
</script>
效果如下:
b.子传父 关键字$parent
和$emit
先设定一个环境,当事件被触发的时候,将值传递过来
a.一个不是很推荐的方法$parent
- 子组件中加一个点击事件,出发后通过
this.$parent.属性名
将值传递 - 父组件在
data
中写方法,然后用胡子语法
渲染到页面
代码如下:
子组件
<template>
<div>
<h2>我是子组件</h2>
<p>父组件传过来的值: {{msg}}</p>
<!-- 子组件给父组件传值 点击事件 -->
<button @click="toFather">给父组件传值</button>
</div>
</template>
<script>
export default {
methods: {
toFather(){
this.$parent.text="这是一个寂寞的天"
}
},
}
</script>
父组件
<template>
<div>
<h1>我是父组件</h1>
<son msg="123"></son>
<p>{{text}}</p>
</div>
</template>
<script>
import son from './son.vue'
export default {
components:{
son
},
data() {
return {
text:''
}
},
}
</script>
效果如下:
注意:一旦涉及到很多的前端插件的使用的时候,我们并不能直接通过 this.$parent.属性名的方法找到他的父组件里面的变量
b.常用方法:$emit
- 子组件中,特定的时候 触发
this.$emit('事件','参数')
- 父组件
<@事件名="自己的方法">
代码如下:
子组件
<template>
<div>
<h2>我是子组件</h2>
<p>父组件传过来的值: {{msg}}</p>
<!-- 子组件给父组件传值 点击事件 -->
<button @click="toFather">给父组件传值</button>
</div>
</template>
<script>
export default {
props:['msg'],
methods: {
toFather(){
this.$emit('xxx','这是一个寂寞的天')
}
},
}
</script>
父组件:
<template>
<div>
<h1>我是父组件</h1>
<son @xxx="getDate"></son>
<p>子组件传过来的值:{{txt}}</p>
</div>
</template>
<script>
import son from './son.vue'
export default {
components:{
son
},
data() {
return {
txt:''
}
},
methods: {
getDate(val){
this.txt=val
}
},
}
</script>
效果如下:
实现过程:
当按钮被点击的时候,触发子组件click的事件,就会调用父组件的getDate
事件,并且把第二个参数床给了methods里面的getDate事件的val
注意事项:子组件的事件名,可以随便写,但是在父组件中,就必须按照子组件中写的事件名来写,@事件名