基础使用
脚手架是什么?
其实就是帮助我们自动化构建和开发项目
每一个以vue作为文件类型的文件,被称为单文件组件 ,分的是三部分,模板、js、css,其中js和css都可以不写,但是模板必须要有
<template></template>
<script></script>
<style scoped></style>
我们写模板的话就直接创建在components内部就可以了
<template>
<div>
我是你自己写的模板
</div>
</template>
这里要遵循之前的模板规则,现在只有一个根元素,不可以有多个
其实基本就是我们之前写的东西,区别就是现在换成文件写,把他都分离开了,分离了之后有一个导入与导出
然后要有一个script用来导出!
<script>
export default {
name:"one"
}
</script>
name是固定名称 one是为了省事,而不是说因为文件名是one这里就是one,这里见名之意就好!!!
导入的话,我们就拿app.js为例子
- 我们需要在script标签内,先写上如下代码
import one from './components/one.vue'
- 然后在写上以下代码
export default {
name: 'App',
components: {
one
}
}
- 最后只需要在模板里调用就可以了
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<one></one>
</div>
</template>
浏览器反馈
整体流程
- 定义好你的组件并且导出,导出名字通常是和文件名是一样的,只是为了省事而已,但是不一直的时候是看name的,与文件名没什么关系
- 引入文件,在组件里去注册一下,然后调用就可以了!
选项卡
根据我们的需求看,我们需要三个按钮,按钮是固定的不需要复用,所以我们把按钮放在app.vue就可以了
<button>one</button>
<button>two</button>
<button>three</button>
然后我们准备三个组件
内容也比较简单,都是只有一个div和一个按钮就可以了
<template>
<div>
我是one
<button @click="next">下一页</button>
</div>
</template>
然后出了第一个,给另外两个组件的div的display都设置为none
注意
直接在style里设置的话,就会使其他div通用,这时我们需要给style加一个scoped,这样你设置的样式只会在当前组件作用域显示,不会共享出去
<style scoped></style>
使用组件前记得导出和注册
<template>
<div id="app">
<button>one</button>
<button>two</button>
<button>three</button>
<one :show.sync="show"></one>
<two :show.sync="show"></two>
<three :show.sync="show"></three>
</div>
</template>
<script>
import one from './components/one.vue'
import two from './components/two.vue'
import three from './components/three.vue'
export default {
name: 'App',
components: {
one,
two,
three
}
}
</script>
我们现在再去给每个按钮设置一个点击事件,并且给他传递一个参数
<button @click="next(1)">one</button>
<button @click="next(2)">two</button>
<button @click="next(3)">three</button>
我们通过参数来决定让那个组件显示
然后在函数里边调接受这个参数,并作相应的处理
export default {
name: 'App',
data(){
return{
show:1
}
},
...
methods: {
next(n){
this.show = n;
}
},
}
然后通过子传父去传递给子级
<one :show.sync="show"></one>
<two :show.sync="show"></two>
<three :show.sync="show"></three>
子级接收到数据后,做出相应的处理,就结束了
export default {
name:"one",
props:["show"],
watch: {
show(){
if(this.show === 1){
this.$el.style.display = "block"
}else{
this.$el.style.display = "none"
}
}
},
methods: {
next(){
this.$emit("update:show",this.show+1)
}
},
}