Vue学习第一节:component和router的使用

以下均是学习过程时当下的理解,仅是记录,对错自辨。

    component

component文件夹需要自己创建,与assets同级。 component不过就是一个小的界面,包含 html、css、js的代码,可以像div一样引用。 创建一个

使用时,在App.vue文件里的<script></script>中的第一行写上:(第二种方法在router里会说)

import firstcomponent from ./component/firstcomponent.vue;

在template

<template>
  <div id="app">
     <firstcomponent></firstcomponent>
  </div>
</template>
    router

main.js文件的配置

import Vue from vue
import App from ./App.vue
import VueRouter from "vue-router";
import VueResource from vue-resource

//开启debug模式
Vue.config.debug = true;

Vue.use(VueRouter);
Vue.use(VueResource);

// 定义组件, 也可以像上面的方法从别的文件引入
import firstcomponent from ./component/firstcomponent.vue
import secondcomponent from ./component/secondcomponent.vue

// 创建一个路由器实例
// 并且配置路由规则
const router = new VueRouter({
          
   
  mode: history,
  base: __dirname,
  routes: [
    // 重定向    这是默认的第一个页面
    {
          
   
      path: /,
      redirect: /first
    },
    {
          
   
      path: /first,
      component: firstcomponent
    },
    {
          
   
      path: /second,
      component: secondcomponent
    }
  ]
})

// 现在我们可以启动应用了!
// 路由器会创建一个 App 实例,并且挂载到选择符 #app 匹配的元素上。
const app = new Vue({
          
   
  router: router,
  render: h => h(App)
}).$mount(#app)

App.vue的代码如下:

<template>
  <div id="app">
    <firstcomponent></firstcomponent>
    <router-view class="view">
    </router-view>
  </div>
</template>

<script>
  import firstcomponent from ./component/firstcomponent.vue;
  export default {
           
    
    name: app,
    data() {
           
    
      return {
           
    
        msg: Hello Vue!
      }
    },
    components: {
           
    
      firstcomponent
    }
  }
</script>

<style lang="scss">
</style>

firstcomponentfirstcomponent.vue的代码在最上面。

router-link就像是a标签

<router-link to="/first">点我去第一个页面</router-link>

router-view就像是html

    动态router

定义方式:在main.js里面,使用 😗* 作为动态的部分

routes: [
    {
          
   
      path: /first/:id,
      component: firstcomponent
    }
   ]

在页面中,比如compotent的代码中,则:

<template>
...略
<div>我是user组件, 动态部分是{
          
   {
          
   id}}</div>
...略
</template>
<script type="text/javascript">
  export default {
          
   
    data() {
          
   
      return {
          
   
        id: this.$route.params.id
      }
    }
  }
</script>

在按钮中的路由跳转则:

methods:{
          
   
  clickFn:function(){
          
   
    this.$router.push({
          
   path:/index});
}

参考:

经验分享 程序员 微信小程序 职场和发展