vue程序之src使用,ref-父传子-子传父使用, props ,混入,插件,插槽,vuex,本地储存,vue-router

Ⅰ vue程序之src使用

  • vue的程序主要是在src中,若是想一直用一个
  • 只需要将上次的src复制一份,改个名即可,不影响 接下来程序的运行
  • 若是想重新运行上次的程序,只需要将现在的src改名,原来的变为src即可

Ⅱ ref-父传子-子传父使用

【一】ref使用

# 1 放在普通标签上
# 2 放在组件上

【二】父传子-子传父

【1】父传子

  • HomeView.vue
<template>
  <div class="home">
  <h1>首页</h1>
    <input type="text" v-model="name">---{{name}}

    <hr>
    <hi ref="hi" :msg="msg"  @send="handlerReceive"></hi>
    <hr>

    <button @click="handlChack" >点我查看控制台拿到的子组件属性</button>


  </div>
</template>

<script>
import hi from "@/components/hi.vue";
export default {
  name: 'HomeView',
  data(){
    return{
      name:'hjj',
      msg:'你是一个大帅逼'
    }
  },
  methods:{
    handlChack(){
      // console.log(this.$refs)
      // console.log(this.$refs.hi.img)
      console.log(this.$refs.hi.username)

      this.$refs.hi.handleClick()
    },
    handlerReceive(username){
      console.log('父组件的被执行了')
      this.name=username
    }
  },
  components:{
    hi
  }
}
</script>

【2】子传父

  • hi.vue
<template>
<div>
  <img :src="img" alt="">
  <h3>{{msg}}</h3>

  <input type="text" v-model="username">--->{{username}}
  <button @click="handleclick">传给父亲</button>

  <hr>
  <button @click="handelcLick">点我查看控制台拿到的父组件属性</button>

</div>
</template>

<style scoped>

</style>


<script>
export default {
  name: "hi",
  data(){
    return{
      img:require('../assets/logo.png'), // 如果引入 视频,音频,图片,js,css资源如果不能用,使用require包裹一下
      username:'子组件'
    }
  },
  methods:{
    handleClick() {
      // alert('hi 子组件')
      alert(this.msg)
    },
    handleclick(){
      this.$emit('send',this.username)
    },
    handelcLick(){
      console.log(this.$parent.name)
    }
  },
  props:['msg']

}
</script>

【三】补充-子组件中拿到父组件对象

 this.$parent
一般不这样用,因为 如果这个子组件给了别的父组件,父组件要是没有 this.$parent 取到的属性,就会报错

【四】总结:父子通信的方式

# 1 自定义属性:   父传子---自定义属性   :msg="msg"
	# 父传
		<child :mytitle="title" :aa="cc" :bb="true"></child>
         data: {
           title:'给你的,儿子',
            cc:'zyb'
               },
      # 子收
       	props:['mytitle','aa'],
            # 子使用
            	<p>{{mytitle}}</p>
            	<p>{{aa}}</p>
            
# 2 自定义事件:   子传父--自定义事件   @send="handlerReceive"
		# 子传
    		 <child  @send_data="handleA"></child>
        		methods:{
            	handleSend(){
                //传给父亲
                // this.$emit('自定义事件名字','参数')
                this.$emit('send_data',this.username)  // <child  @send_data="handleA"></child>
           				 }
      			  }

		# 父收
       		 methods: {
            	handleA(name){  // handleA(name)  是给传过来的数据重新命名 如 handleA(b)
                this.name=name  	//  this.name=b  将传过来的数据 放入父属性中
           			 }
        			}
                # 父用
                	<p>这是父组件,子组件传过来的值是:{{name}}</p>
        
# 3 通过ref属性:this.$refs
      # 使用 
    	<hi ref="hi" :msg="msg"  @send="handlerReceive"></hi>
            # 拿到子属性
            	 console.log(this.$refs.hi.username)
  

# 4 子组件中通过 this.$parent

Ⅲ props

第一种方式(只接收):props:['name']

第二种方式(限制类型):props:{name:String}

第三种方式(限制类型、限制必要性、指定默认值):


#  父传子时,自定义属性,在子组件中声明,才能使用当前属性
	  # 1 方式一:
        props:['msg'],
      # 2 方式 二 
        props: {myname: String},   //  如果:msg="true"  是布尔类型   props里面是需要string  在控制台就会报错
      # 3 方式三  
        props: {
            myname: {
              type: String, //类型
              required: true, //必要性
              default: '老王' //默认值   如果不传  页面上会显示 "老王"  但是控制台会报错  传了 页面就是传的数据 控制台也不会报错
            }
          },

Ⅳ 混入

mixin(混入)
功能:可以把多个组件共用的配置提取成一个混入对象

#  抽取公共的代码,  相当于类中将相同的功能函数进行封装
	-多个组件中都会有的代码,抽出来
    -哪个组件用,使用mixin引入即可

【一】问题引入

  • HomeView.vue
<template>
  <div class="home">
    <h1>首页</h1>
    <h2>我的名字是:{{username}}</h2>
    <button @click="changName('变猪')">点我变猪</button>
    {{hobby}}


  </div>
</template>

<script>

export default {
 	name: 'HomeView',   
    data(){
      return {
        hobby:'抽烟,喝酒,烫头'
        username:'ggb'
      }
      },
      methods:{
        changName(name){
          this.username=name
        }
      }

    }
</script>
  • AboutView.vue
<template>
  <div class="home">
  <h1>这是About</h1>
    <h2>我的名字是:{{username}}</h2>
    <button @click="changName('容嬷嬷')">点我变容嬷嬷</button>


  </div>
</template>

<script>


export default {
	name: 'HomeView',   
    data(){
      return {
        username:'ggb'
      }
      },
      methods:{
        changName(name){
          this.username=name
        }
      }

    }
</script>

【二】抽取公共的代码

  • 重新建一个文件夹,放公共的代码
  • index.js
export default {

  data(){
  return {
    username:'ggb'
  }
  },
  methods:{
    changName(name){
      this.username=name
    }
  }

}

【三】局部使用

  • HomeView.vue
<template>
  <div class="home">
    <h1>首页</h1>
    <h2>我的名字是:{{username}}</h2>
    <button @click="changName('变猪')">点我变猪</button>
    {{hobby}}


  </div>
</template>

<script>
import m1 from "@/minxin";
export default {
  name: 'HomeView',
  data(){
    return {
      hobby:'抽烟,喝酒,烫头'

    }
  },
  methods:{


  },
  mixins:[m1]


}
</script>

  • AboutView.vue
<template>
  <div class="home">
  <h1>这是About</h1>
    <h2>我的名字是:{{username}}</h2>
    <button @click="changName('容嬷嬷')">点我变容嬷嬷</button>


  </div>
</template>

<script>

import m1 from "@/minxin";

export default {
  name: 'AboutView',
  data(){
  return {

  }
  },
  methods:{


  },
  mixins:[m1]

}
</script>

【四】全局使用

  • main.js
// 再main.js中导入 设置成全局使用
import m1 from "@/minxin";
Vue.mixin(m1)

【五】总结

#  使用方式
	-方式一:某个组件中使用
        import m1 from '@/mixin'
        export default {
          data() {
            return {
              hobby:'烫头'
            }
          },
          methods: {

          },
          mixins:[m1,m2]  # 如果是多个  局部使用 [m1,m2]
        }
    -方式二:所有组件中使用 main.js
        import m1 from '@/mixin'
        import m2 from '@/mixin2'
        Vue.mixin(m1)
        Vue.mixin(m2)  # 如果是多个  全局使用 要都设置
    

Ⅴ 插件

# 功能:用于增强Vue

# 本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据

# 使用了vue-router插件,vuex插件,elementui
	this.$router
    this.$store
    this.$alert
    this.$message
	
#  使用别人写好的第三方插件
	Vue.use(ElementUI);


import axios from "axios";
import m1 from '@/mixin'
export default {
    install(Vue,a) {
        console.log(a)
        // console.log('自定义插件执行了:', Vue)
        // 插件中可以干什么?
        // 1 定义全局变量,放到原型中 向Vue原型中放变量-->后续所有的组件中都可以通过  this.$ajax  拿到这个变量
        // prototype 原型链,一般定义在原型中的变量,都用 $ 开头,防止污染--->对象中可以定义同名属性,冲突
        // Vue.prototype.$ajax='xxxxooo'
        Vue.prototype.$BASE_URL='http://127.0.0.1:8000/api/v1/'
        // 2 把axios对象放到原型中
        Vue.prototype.$ajax=axios

        // 3 定义指令  自定义指令  -->可能第三方插件,咱们项目中用了后,会有没见过的指令
        
        //定义全局指令:跟v-model一样,获取焦点
        Vue.directive("fbind", {
            //指令与元素成功绑定时(一上来)
            bind(element, binding) {
                element.value = binding.value;
            },
            //指令所在元素被插入页面时
            inserted(element, binding) {
                element.focus();
            },
            //指令所在的模板被重新解析时
            update(element, binding) {
                element.value = binding.value;
            },
        });

        // 4 使用混入-->可能第三方插件,咱们项目中用了后,在组件中会有 默认的变量和方法
        Vue.mixin(m1)

        // 5 定义全局组件
        // elementui-->全局组件    <el-button>
        // vue-router-->全局组件  router-view

    }
}

#  在main.js中使用,可以传参数
#  使用自定义插件
import my from '@/plugins'
Vue.use(my,'zyb') // 内部本质会执行install


# 咱们需要掌握的;
	-有些第三方插件,用了以后,增强了vue功能
    -this.$router
    -全局组件 :el-button
    -this.$message--->
    -this.$http.get

Ⅵ 插槽

  1. 作用:让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于 父组件 ===> 子组件
  2. 分类:默认插槽、具名插槽
  • HelloWorld.vue


<template>
  <div>
    <slot name="b"></slot>
    <h2>我是helloworld组件</h2>
    <slot name="a"></slot>

  </div>



</template>

<style scoped>

</style>

<script>
export default {
  name: "HelloWorld"
}
</script>

  • AboutView.vue
<template>
  <div class="home">
  <h1>这是About</h1>
    <helloWorld>
      
      <div slot="a">
        <img src="https://img2.baidu.com/it/u=3119168203,3932583464&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=800" alt="">
      </div>

      <div slot="b">
        <h3>画画的baby</h3>
      </div>


    </helloWorld>


  </div>
</template>

<script>

import helloWorld from "@/components/HelloWorld.vue";

export default {
  name: 'AboutView',
  data(){
    return{

    }
  },
  methods:{

  },
  components:{
    helloWorld
  }


}
</script>

Ⅶ vuex

# 第三方插件:状态管理器-->管理状态-->管理变量的--->统一的位置管理变量-->实现组件间通信
	-vue2 :vuex
    -vue3:vuex,pinia:用的多
    
    
#  使用vuex 
	-创建项目时候,已经装了
    	-项目依赖有了
        -项目中有个 store文件夹-->index.js
        -main.js 中,引入且使用了
        
    -在创建项目时,没装
    	-安装:cnpm install vuex@3.6.2   # @3.6.2 意思是指定版本安装
        	 cnpm install element-ui@2.15.14 -S  # -S 意思是以后版本信息会保存到package.json 重新装models依赖时候 会装上
        -在项目中新建 store-->index.js
        	-在index.js中写入代码
                import Vue from 'vue'
                import Vuex from 'vuex'
                Vue.use(Vuex)
                export default new Vuex.Store({
                  state: {
                  },
                  mutations: {
                  },
                  actions: {
                  }
                })
        在main.js中使用
        	import store from './store'
            new Vue({
                store,
                render: h => h(App)
            }).$mount('#app')

            
            
# 3 具体使用



# 4 作用和好处
	-1 降低代码耦合度
    -2 实现组件间通信

  • 相当于你去饭店吃饭,你先跟服务员点菜,然后服务员让厨师去做出来拿过来给你吃
  • 先调用dispatch,再触发commit,在mutations执行 ,然后你把修改后的state传出来 给我
  • 后期熟练之后你就不用再按部就班,你可以直接告诉厨师做,甚至于你可以自己动手做–>但是自己做可能会出错,按部就班准确率高

【一】直接操作

  • HomeView.vue
<template>
  <div class="home">
  <h1>这是首页</h1>

    <h3>vue中的count变量:{{$store.state.count}}</h3>
    <button @click="handleAdd">点我加一</button>



  </div>
</template>

<script>


export default {
  name: 'HomeView',
  methods:{
    handleAdd(){
      // 1.相当于 直接自己去炒饭   直接操作
       this.$store.state.count++
       console.log(this.$store.state.count)
    }
  }
}
</script>

  • store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count:0
  },
  mutations: {   
  },
  actions: {
  },
})

【二】按部就班先dispatch,再commit,还能增加额外校验

  • HomeView.vue
<template>
  <div class="home">
  <h1>这是首页</h1>

    <h3>vue中的count变量:{{$store.state.count}}</h3>
    <button @click="handleAdd">点我加一</button>



  </div>
</template>

<script>


export default {
  name: 'HomeView',
  methods:{
    handleAdd(){

      // 按部就班 先dispatch,再commit
      this.$store.dispatch('addCount')

    }
  }
}
</script>

  • store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count:0
  },
  mutations: {
    add(state){
      state.count+=1
    }
  },
  actions: {
    addCount(ctx){
      // 通知 mutations 更新变量 触发add的执行--> 相当于 服务员告诉厨师炒菜
      if(ctx.state.count>=5){  // 还能增加额外校验 
        alert('不能再加了')
      }else {
        ctx.commit('add')
      }
    }
  },

})

【三】直接 commit --> 相当于直接告诉厨师

  • HomeView.vue
<template>
  <div class="home">
  <h1>这是首页</h1>

    <h3>vue中的count变量:{{$store.state.count}}</h3>
    <button @click="handleAdd">点我加一</button>



  </div>
</template>

<script>


export default {
  name: 'HomeView',
  methods:{
    handleAdd(){
      // 3. 直接 commit  --> 相当于直接告诉厨师
      this.$store.commit('add')

    }
  }
}
</script>

  • store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count:0
  },
  mutations: {
    add(state){
      state.count+=1
    }
  },
})
  • 还能再传参数
  • HomeView.vue
<template>
  <div class="home">
  <h1>这是首页</h1>

    <h3>vue中的count变量:{{$store.state.count}}</h3>
    <button @click="handleAdd">点我加一</button>



  </div>
</template>

<script>


export default {
  name: 'HomeView',
  methods:{
    handleAdd(){
      // 1.相当于 直接自己去炒饭   直接操作
      // this.$store.state.count++
      // console.log(this.$store.state.count)

      // 2.按部就班 先dispatch,再commit  -->  相当于 服务员告诉厨师炒菜
      // this.$store.dispatch('addCount',2)  // 这里也还能传参

      // 3. 直接 commit  --> 相当于直接告诉厨师
      this.$store.commit('add',2)   // 这里还能传参

    }
  }
}
</script>

  • store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count:0
  },
  mutations: {
    add(state,number){    //  这里是接收的 this.$store.commit('add',2) 传参 也能接收ctx.commit('add',number)传的 number
      state.count+=number
    }
  },
  actions: {
    addCount(ctx,number){   //  接收的  this.$store.dispatch('addCount',2) 传参
      // 通知 mutations 更新变量 触发add的执行--> 相当于 服务员告诉厨师炒菜
      if(ctx.state.count>=5){
        alert('不能再加了')
      }else {
        ctx.commit('add',number)
      }
    }
  },

})

【四】组件中使用

#  组件中使用
	// 子组件 HelloWorld.vue   template中使用  :
		<h3>vuex中得count变量:{{$store.state.count}}</h3>

	- 父组件 AboutView.vue  template中使用 
    	<button @click="handleAdd">加入购物车</button>
        	methods:{
                handleAdd(){
                  this.$store.state.count+=1
                }

              },
        


    -js中使用:
          #1 直接操作
          this.$store.state.count++
          console.log(this.$store.state.count)

          # 2 正统-->先dispatch-->再commit
           this.$store.dispatch('addCount',2)
          # 3 直接commit
          this.$store.commit('add',3)
        
        
#  为什么经过 actions和mutations 
    -可以跟后端交互,可以做数据验证

#  getters:
    	可以通过getters获取数据-->对state中的数据,再做处理
    # 使用   HomeView.vue
    		 <h3>vuex中得count变量:{{$store.getters.getCount}}</h3>
         -js中使用: 
                     getters: {
                        getCount(state) {
                            return state.count + 100
                        }
                    },

#  modules:
    	分到不同模块中,不同模块有自己的state,actions

Ⅷ 本地存储

#  能存储数据的位置,登录成功--->token存储
	vuex: 页面重新加载-->数据会恢复
	cookie:登录信息放这里,有过期时间,一旦过期,就没了
    sessionStorage:当前浏览器生效--->关闭浏览器,数据就没了
    localStorage:永久生效,除非代码删除或清空浏览器缓存
    	-未登录,加购物车
        
        
# cookie 需要下载 vue-cookies
cnpm install vue-cookies -S

<template>
  <div class="home">
  <h1>这是首页</h1>

    <h2>localStorage</h2>
    <button @click="handleSaveLocalStorage">存储到localStorage</button>
    <button @click="handleGetLocalStorage">从localStorage取出</button>
    <button @click="handleDeleteLocalStorage">删除localStorage</button>

    <h2>sessionStorage使用</h2>
    <button @click="handleSavesessionStorage">存储到sessionStorage</button>
    <button @click="handleGetsessionStorage">从sessionStorage取出</button>
    <button @click="handleDeletesessionStorage">删除sessionStorage</button>
    <h2>cookie使用</h2>
    <button @click="handleSaveCookie">存储到cookie</button>
    <button @click="handleGetCookie">从cookie取出</button>
    <button @click="handleDeleteCookie">删除cookie</button>


  </div>
</template>

<script>


export default {
  name: 'HomeView',
  methods: {
    handleSaveLocalStorage() {
      localStorage.setItem("name", 'zyb')
      let user = {
        name: 'xxx',
        age: 19
      }
      localStorage.setItem("user", JSON.stringify(user)) // 不要放对象  // 在控制面板数据中 他是个字符串

    },
    handleGetLocalStorage() {
      let name = localStorage.getItem("name")
      let user = localStorage.getItem('user')
      console.log(name)
      console.log(user)
      console.log(typeof user)

    },
    handleDeleteLocalStorage() {
      // localStorage.removeItem('name')
      localStorage.clear()

    },




    handleSavesessionStorage() {
      sessionStorage.setItem("name", '彭于晏')
    },
    handleGetsessionStorage() {
      let name = sessionStorage.getItem('name')
      console.log(name)
    },
    handleDeletesessionStorage() {
      sessionStorage.removeItem('name')
      // sessionStorage.clear()
    },



    handleSaveCookie() {
    this.$cookies.set('name', 'zzzz', '100s')
    },
    handleGetCookie() {
      let name = this.$cookies.get('name')
      console.log(name)
    },
    handleDeleteCookie() {
      this.$cookies.remove('name')
      // this.$cookies.clear()

    },
  }
}
</script>

  • main.js
// 使用vue_cookies
import cookies from 'vue-cookies'
Vue.prototype.$cookies=cookies

Ⅸ vue-router

#  如果我们创建项目时,已经安装了
	-router-->项目中就会显示 index.js
    -main.js 引入了
    -后期在组件中:
    	-js中:
            this.$router # 跳转路径
            this.$route   # 目前不管
        -template中:
        	<router-view/>  # 当访问某个路径时,会把页面组件替换到这
            <router-link></router-link>
            
#  创建项目没有安装,自行引入
	-创建文件夹router---index.js
    -index.js写代码
    import Vue from 'vue'
    import VueRouter from 'vue-router'
    import HomeView from "@/views/HomeView";
    Vue.use(VueRouter)
    const routes = [
        {
            path: '/',
            name: 'home',
            component: HomeView
        },

    ]
    const router = new VueRouter({
        mode: 'history',
        base: process.env.BASE_URL,
        routes
    })
    export default router

    
    
    	
    -main.js中使用
        import router from './router'
        new Vue({
            router,
            render: h => h(App)
        }).$mount('#app')
        
   -后续所有组件中
	    -js中:
            this.$router # 跳转路径
            this.$route   # 目前不管
        -template中:
        	<router-view/>  # 当访问某个路径时,会把页面组件替换到这
            <router-link></router-link>

【一】路由跳转

# 在App.vue中放 
  <div id="app">
    <router-view/>
  </div>
#  在router---index.js中-->注册路径-->routes
    const routes = [
            {
                path: '/',
                name: 'home',
                component: HomeView
            },

        ]
#  以后访问某个路径,就会显示页面组件


# 重点:页面跳转两种方式
	# 1 js跳转
       // 1 传路径
      // this.$router.push('/about')
      // 2 传对象
      // this.$router.push({'name': 'about'})
      // this.$router.push({'path': '/about'})

      // 携带参数跳转
      // this.$router.push('/about?name=lqz&age=19')
      // this.$router.push({'name': 'about',query:{name:'zhangsan',age:19}})
      this.$router.push({'path': '/about',query:{name:'zhangsan',age:19}})
        
   # 2 template中跳转:router-link组件
        <router-link to="/about">
           <button>点我跳转到about页面-router-link</button>
        </router-link>

        <router-link :to="{name:'about',query:{name:'xxx'}}">
           <button>点我跳转到about页面-router-link</button>
        </router-link>

# 重点 上个页面跳转时,携带数据(查询参数)--->下一个页面中取出来
	-在下一个页面中写:AboutView.vue
    -写在created中
        this.book_id=this.$route.query['book_id']
        #this.book_id=this.$route.query.book_id
        #console.log(this.$router) // VueRouter 的对象
        #console.log(this.$route)  // 当前路由对象
        
        
#  重点 上个页面跳转时,携带数据(查询参数)--->下一个页面中取出来
	1 路由写法变了
    	 {
            path: '/:pk/lqz',
            name: 'lqz',
            component: LQZView
        },
   2 传递数据
		-js:
    		this.$router.push("/99/lqz")
        	this.$router.push({name:'lqz',params:{pk:666}})
    	-router-link:
          <router-link to="/99/lqz">
    	  <router-link :to="{name:'lqz',params:{pk:666}}">
            
  3 另一个页面获取数据
	this.$route.params.pk

【1】js跳转

<template>
  <div class="home">
  <h1>这是首页</h1>
    <button  @click="handleGo">点击跳转about页面</button>



  </div>
</template>

<script>


export default {
  name: 'HomeView',
  methods:{
    handleGo(){
      // 1 传路径
      // this.$router.push('/about')
      // 2 传对象
      // this.$router.push({'name': 'about'})
      // this.$router.push({'path': '/about'})

      // 3 携带参数跳转
      // this.$router.push('/about?name=zhangsan&age=19')
      // this.$router.push({'name': 'about',query:{name:'zhangsan',age:19}})
      // this.$router.push({'path': '/about', query: {name: 'zhangsan', age: 19}})
    }
  }

}
</script>

【2】template中跳转:router-link组件

<template>
  <div class="home">
  <h1>这是首页</h1>
    <button  @click="handleGo">点击跳转about页面</button>

    <router-link to="/about">
           <button>点我跳转到about页面-router-link</button>
        </router-link>

        <router-link :to="{name:'about',query:{name:'xxx'}}">
           <button>点我跳转到about页面-router-link</button>
        </router-link>



  </div>
</template>

【3】上个页面跳转时,携带数据(查询参数)--->下一个页面中取出来

  • HomeView.vue –> query:{book_id:'99'}}
<template>
  <div class="home">
  <h1>这是首页</h1>
    <button  @click="handleGo">点击跳转about页面</button>

<!--    <router-link to="/about">-->
<!--           <button>点我跳转到about页面-router-link</button>-->
<!--        </router-link>-->

        <router-link :to="{name:'about',query:{book_id:'99'}}">
           <button>点我跳转到about页面-router-link</button>
        </router-link>



  </div>
</template>
  • AboutView.vue


<template>
  <div>
    <h1>我是about</h1>

    <h2>上个页面传入的book_id是:{{book_id}}</h2>

  </div>

</template>

<style scoped>

</style>


<script>
export default {
  name: "AboutView",
  data(){
    return{
      book_id:''
    }
  },
  created() {
    console.log(this.$router)  // VueRouter 的对象
    console.log(this.$route)  // Object  当前路由对象
                          // 路由对象  {
                              //   path: '/about',
                              //   name: 'about',
                              //   component: AboutView
                              // },


      this.book_id=this.$route.query['book_id']
      // this.book_id=this.$route.query.book_id
      // console.log(this.$router) // VueRouter 的对象
      // console.log(this.$route)  // 当前路由对象
  }
}
</script>

【4】上个页面跳转时,携带数据(路径参数)--->下一个页面中取出来

#  重点 上个页面跳转时,携带数据(查询参数)---》下一个页面中取出来
	1 路由写法变了
    	  {
            path: '/:pk/path',
            name: 'path',
            component: PathView
          },
   2 传递数据
		-js:
    		this.$router.push("/99/path")
        	this.$router.push({name:'path',params:{pk:666}})
    	-router-link:
          <router-link to="/99/path">
    	  <router-link :to="{name:'path',params:{pk:666}}">
            
  3 另一个页面获取数据
	this.$route.params.pk

【二】相关api

1 指的是:this.$router--->方法
2 常用的
this.$router.push(path): 相当于点击路由链接(可以返回到当前路由界面)
this.$router.replace(path): 用新路由替换当前路由(不可以返回到当前路由界面)
this.$router.back(): 请求(返回)上一个记录路由
this.$router.go(-1): 请求(返回)上一个记录路由
this.$router.go(1): 请求下一个记录路由

【三】多级路由

  • router-index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from "@/views/HomeView.vue";
import AboutView from "@/views/AboutView.vue";
import PathView from "@/views/PathView.vue";
import MulRouterView from "@/views/MulRouterView.vue";
import IndexView from "@/views/pages/IndexView.vue";
import GoodsView from "@/views/pages/GoodsView.vue";
import OrderView from "@/views/pages/OrderView.vue";


Vue.use(VueRouter)

const routes = [


     {
    path: '/',
    name: 'home',
    component: HomeView
  },
    {
    path: '/about',
    name: 'about',
    component: AboutView
  },
    {
    path: '/:pk/path',
    name: 'path',
    component: PathView
  },
    {
        path: '/mul',
        name: 'mul',
        component: MulRouterView,
        children: [ //通过children配置子级路由
            {
                path: '', //此处一定不要写:/news
                name:'index',
                component: IndexView
            },
            {
                path: 'order',
                name:'order',
                component: OrderView
            },
            {
                path: 'goods',
                component: GoodsView
            }
        ]
    },


]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

  • 使用elementui 先引入
  • main.js
//elementui的引入
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);
  • MulRouterView.vue
<template>
  <div>

    <div style="height: 80px;background-color: pink"></div>


    <el-container>
      <el-aside width="200px">
        <div style="background-color:greenyellow;height:700px ">
          <p><router-link to="/mul">首页</router-link></p>
          <p><router-link :to="{name:'order'}">订单</router-link></p>
          <p><router-link to="/mul/goods">商品</router-link></p>
        </div>
      </el-aside>
      <el-container>
        <el-header>
          <div style="background-color:rebeccapurple"></div>
        </el-header>
        <el-main>
          <div style="height:500px;background-color: aqua">

            <router-view></router-view>



          </div>
        </el-main>
        <el-footer>
          <div style="background-color: pink;height:50px"></div>
        </el-footer>
      </el-container>
    </el-container>

  </div>
</template>

<script>
export default {
  name: "MulRouterView"
}
</script>

<style scoped>

</style>
  • 三个不同页面放在文件夹 pages 下

  • IndexView.vue

<template>
<div>
  <h1>后台首页</h1>
</div>
</template>

<script>
export default {
  name: "IndexView"
}
</script>

<style scoped>

</style>
  • GoodsView.vue
<template>
  <div>
    <h1>商品</h1>
  </div>
</template>

<script>
export default {
  name: "GoodsView"
}
</script>

<style scoped>

</style>
  • OrderView.vue
<template>
<div>
  <h1>订单</h1>
</div>
</template>

<script>
export default {
  name: "OrderView"
}
</script>

<style scoped>

</style>
  • 前端展示

posted on   silence^  阅读(118)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
点击右上角即可分享
微信分享提示