scoped作用:设置样式只在当前页面起效果
1.ref使用
ref被用来给元素或子组件注册引用信息。引用信息将会注册在父组件的$refs对象上。如果在普通的 DOM 元素上使用,引用指向的就是DOM元素;如果用在子组件上,引用就指向组件实例。
相当于通过ref转换,变成原生的了。
//这是parent.vue
<div>
<div class="box" ref='box1'>我是父组件</div>
<vChild ref="child"></vChild>
<button @click="get">点击获取</button>
</div>
methods: {
get(){
// console.log(this.$refs.box1.offsetWidth)
//父组件调用子组件的方法实现修改子组件的内容
console.log(this.$refs.child.changeName())
}
},
//这是child.vue
<template>
<div>
<div ref="inner">我是子组件</div>
</div>
</template>
<script>
export default {
components: {},
data() {
return {};
},
methods: {
changeName(){
// 在方法中,如果没有返回值,会默认返回一个Undefined
this.$refs.inner.innerText = '我被修改了'
}
},
}
</script>
2.路由的使用
vue中的路由做的是组件之间的跳转,一个地址里面可能有好多个组件。所以路由配置就是配置路径以及和哪些组件有关系。
1.路由的基本使用
1.npm install vue-router --save
2.在main.js中引入
import Router from 'vue-router'
Vue.use(Router)
const router = new Router({
//配置规则
routes:[
{
path:'/login',
component:login
}
]
})
new Vue({
router,
})
3.在页面增加需要跳转的按钮
<router-link to='/login'>跳转</router-link>
4.在哪里显示组件的内容 需要添加路由出口
<router-view></router-view>
2.路由的嵌套
这是login.vue中
<div>
<h1>我是login页面</h1>
<!-- 路由出口 -->为了在页面显示要加载的组件
<router-view></router-view>
<router-link to="/login/index">首页</router-link>
<router-link to="/login/food">美食</router-link>
<router-link to="/login/mine">我的</router-link>
<router-link to="/register">点击跳转注册</router-link>
</div>
在路由main.js中配置
const router = new Router({
// 路由规则
routes:[
{
path:'/login',
component:login,
// 二级路由 path不需要加/ 同时重定向path为空即可
children:[
{
path:'index',
component:index,
},
{
path:'food',
component:food,
},
{
path:'mine',
component:mine,
},
{
path:'',
redirect:'food',
}
]
})
3.项目配置
----src
----assets
-img
-css
-js
----components 拼接页面存放的组件
----pages 页面组件
----common 公共组件
----filter 过滤器
----util 工具类
4.编程式导航
this r o u t e r . p u s h t h i s . router.push this. router.pushthis.route.replace
<!-- --1.router-link--- -->
<router-link to='/movie'>电影</router-link>
<router-link to='/food'>美食</router-link>
<!-- 2.$router.push -->
<button @click="toMovie">电影</button>
<button @click="toFood">美食</button>
<!-- 3.$router.replace -->
<button @click="toMovie1">电影1</button>
<button @click="toFood1">美食1</button>
总结:
1.没有约束条件时跳转,用router-link
2.push 是一级一级的往上返回 相当于增加一条新的历史记录
3.replace 是直接返回最开始位置,相对替换上一条历史记录
5.动态路由
在router中的index.js中修改
{
path:'/movieDetail/:id',
component:movieDetail,
}
在movie中增加点击跳转方法:
toDetail(id){
this.$router.push('/movieDetail/'+id)
console.log(id)
}
通过?传参方式 需要注意路由匹配规则 path:'/movieDetail/:id' 一定不要添加:id
<ul>
<li is='router-link' :to="'/movieDetail?'+item.id" v-for='item in list' :key='item.id'>
<p>{{item.name}}</p>
<p>{{item.time}}</p>
<p>{{item.price}}</p>
</li>
</ul>
6.封装公共组件
commin.js
<div>
<button @click="$router.go(-1)">返回</button>
</div>
通过common文件夹下面的index导出所有的公共组件,同时需要注册到main.js中
通过Index导出来,拳距离注册的时候不需要一个个引入了,因为在index里都引了。在Main中循环遍历注册到全局上。
//main.js中
import Components from './common/index'
for(let i in Components){
// {k:v}{k:v}
// Vue.component('vBack',vBack)
Vue.component(i,Components[i])
}