Vue学习笔记2

142 阅读4分钟

上篇文章总结

  • vue单文件方式 xxx.vue
  • 1:准备好配置文件 package.json(包描述文件&& 封装命令npm run dev) + webpack.config.js文件(打包的配置文件)
  • 2:创建index.html(单页应用的页)
  • 3:创建main.js(入口文件)
  • 4:引入vue和相关的文件xxx.vue
  • 5:new Vue(options)
  • 6:options(选项):
    • data
    • methods
    • components(组件内声明子组件)
    • props
  • 7:实例:
    • 在组件内(xxx.vue)中的this
    • new Vue()
    • 事件
      • this.$on(事件名,回调函数(参数))
      • this.$emit(事件名,数据)
      • this.$once(事件名,回调函数(参数)) 就触发一次
      • this.$off(事件名); 取消事件
  • 8:全局
    • Vue.component('组件名',组件对象) 在哪里都可以使用
  • 9: 组件传值
    • 父传子: 属性作为参数
      • 常量 title="xxx" 子组件声明接收参数 props:['xxx']
      • 变量 :title="num" 子组件声明接收参数 props:['xxx']
    • 子传父: vuebus(只能是同一辆车)
      • 先停车到父组件,On一下
      • 再开车到子组件,如果需要的话,emit一下,触发上述时间的回调函数

1.vue 组件

  • 创建子组件
    • <template></template> 中创建根div 写html代码
    • <script></script>export default {data(){ return{}}} 写js代码
    • 中写css 样式
  • 再父组件中
    • 引入自组件 + 在components:{}中声明组件
      import headerVue from './components/header.vue';
      import bodyVue from './components/body.vue';
      import footerVue from './components/footer.vue';
      export default {
          data(){  return {  }  },
          methods:{},
          //必须声明
          components:{
              //组件名(在模板中使用) :组件对象
              headerVue:headerVue,
              bodyVue, //简写
              footerVue
          }
      }
      
    • template中 使用组件 <header-vue></header-vue>
  • 声明全局组件 再main.js中 引入,使用全局方法Vue.component('headerVue',headerVue)
    //引入子组件对象
    import headerVue from './components/header.vue';
    import bodyVue from './components/body.vue';
    import footerVue from './components/footer.vue';
    //声明全局组件
    Vue.component('headerVue', headerVue); //注册一个组件,第一个参数是名称,在template中使用,第二个参数是实际的对象,显示成什么内容,具备什么功能
    Vue.component('bodyVue', bodyVue);
    Vue.component('footerVue', footerVue);
    

2.vue 组件间传值 父传子

  • 父组件使用 key='value'v-bind:key='本父组件.key'
    <header-vue textone="大"></header-vue>
    <body-vue v-bind:texttwo="text2"></body-vue>
    
  • 使用使用propos
    • 再html中使用props的属性不需要使用this
    • props和data一样是一组件的选项/数据 //接受父组件值参数的设置props:['textone'],
    • 再方法中使用props需要使用this‘
      export default {
          data(){
              return {}
          },
          //接受父组件值参数的设置
          props:['textone'],
          methods:{
              show(){
                  alert(this.textone)
              }
          }
      }
      

2.vue 组件间传值 子传父组件

  • 需要借助一个中间值 conneor.js 是一个Vue实力
    import Vue from 'vue';
    var connector = new Vue();
    export default connector;
    
  • 子组件传值 ,先引用实例 调用实例方法使用$emit 发送信息connnet.$emit(事件名,[...args])
    import connect from '../connector.js';
    connect.$emit('phone','62分钟来');
    
  • 在父组件中 先引用实例 调用实例方法使用$on 发送信息connnet.$on(事件名,callback) 回调函数的参数是emit发送的参数
    connect.$on('phone',function(msg){
        console.log(msg);
    })
    
  • vm.$once(event,calback) 事件触发一次,触发之后移除监听器。
  • vm.$off(event,callback) 移除事件监听
    • 如果没有参数,移除所有的监听
    • 如果只有一个事件参数,移除这个事件的监听
    • 有事件参数 又回调参数,移除这个回调的监听

3.过滤器

  • filters {{text | filter1}}局部/全局过滤器
    • 局部过滤器 在选项options /资源 设置 filter1:function(value){return newValue}
      myFilter:function(value){  //value 就是-> text
          //输入的内容帮我做一个反转
          //转换成数组,反转数组,转换成字符串
          return value.split('').reverse().join('');
      }
      
    • 设置全局过滤器 全局API Vue.filter(id,function)
      // 注册
      Vue.filter('my-filter', function (value) {
      // 返回处理后的值
      })
      
      // getter,返回已注册的过滤器
      var myFilter = Vue.filter('my-filter')
      
    • 全局过滤器范围大,但会被局部的覆盖,
    • 组件内过滤器 如果同名会覆盖,但是使用范围没有全局广 进行不实用同名过滤器

4.Vue 实例属性 获取dom

  • html使用ref='r1'标记 在方法内使用 vm.$refs.r1获取
    • 生命周期函数 creat() 组件创建后 数据已完成初始化但是DOM还未完成
    • 生命周期函数 mounted() 数据装在Dom上后,各种数据已经就位将数据渲染Dom上,DOM已经生成
  • 在模版内代码
    <div ref="myDiv">
    <sub-vue ref="sub"></sub-vue>
    
  • 在script代码获取dom
    • 操作原生的Dom this.$refs.myDiv
      // 涉及DOM类的操作
      // this.$refs.myDiv.innerHTML = '哈哈呵呵';
      
    • 获取标记组件对象 this.$refs.sub ,获取组件的原生dom this.$refs.sub.$el Vue 实例使用的根 DOM 元素
      // console.log('sub:',this.$refs.sub.$el);
      //获取组件对象,并获取到其的DOM对象
      this.$refs.sub.$el.innerHTML = '嘻嘻';
      

5.Vue 其他实例属性

  • vm.$data 数据对象 可以读写
  • vm.$props props对象 数据
  • vm.$el 根DOM 元素
  • vm.$options 方便获取options.customOption
  • vm.$parent 获取父实例
  • vm.$root 当前组件的根Vue
  • vm.$children 直接子实例s 数组无序
  • vm.slots  插槽内容 讲再父组件文件内使用的时候子文件双标签之间的内容,传入子组件的显示。`<slot></slot>` `vm.slots `最有帮助。
  • vm.$scopedSlots 作用域插槽 { [name: string]: props => VNode | Array<VNode> }
  • vm.$refs 获取所有设置过ref的dom和组件
  • vm.$isServer 当前Vue是否运行于服务器
  • vm.$attrs { [key: string]: string } 只读不能写入 不被prop识别的属性值
  • vm.listeners 包含了父作用域中的 (不含 .native 修饰器的) `v-on 事件监听器`。它可以通过 `v-on="listeners"` 传入内部组件——在创建更高层次的组件时非常有用。

6.Vue-router 路由

  • 前端路由核心是锚点值的改变 根据不同的值,渲染指定DOM的不同数据window.addEventListener(hasCahnged,function) 监听路由的哈希值的改变

    //监视锚点值的改变
    
    window.addEventListener('hashchange', function() {
        var text = '';
        switch (location.hash) {
            case '#/music':
                text = '各种音乐的数据';
                break;
            case '#/movie':
                text = '各种电影的数据';
                break;
        }
        document.getElementById('content').innerHTML = text;
    })
    
  • mian.js 中 也可以在router/index.js

  • 引入vue-router

  • 全局APIVue.use(VueRouter) 挂在属性

  • 创建VueRouter({options})实例

  • vue的option 中赋值路由规则

    Vue.use(VueRouter); //挂载属性
    //创建路由对象并配置路由规则
    let router = new VueRouter({
        //routes
        routes: [
            //一个个对象
            { path: '/home', component: Home }
        ]
    });
    //new Vue 启动
    new Vue({
        el: '#app',
        //让vue知道我们的路由规则
        router: router, //可以简写router
        render: c => c(App),
    })
    
  • 路由参数 在初始化routers 路径数组。里面是一个一个路由对象{name:'name',path:'/lisl',component:实例}

  • 路由参数 查询字符串方式传参数 path:'/detail'

    • 浏览器url是 /detail? xxx = xx & xxx = xxx 查询多少字符串都不用修改path
    • 父组件传参数方式 使用query
      • 在html内 <router-link :to="{name:detail,query:{id:index}}"></router-link>
      • 在js中使用this.$router.push({name:detail,query:{id:index}})
      • 子组件获取参数方式 使用this.$router.query
  • 以path拼接的方式使用 path:'/detail/:id'

    • 浏览器的Url是/detail/12
    • 父组件传参数使用pramas
      • 在html 中使用<router-link :to="{name:detail,pramas:{id:index}}"></router-link>
      • 在js中使用
        this.$router.push('/detail/'+ index)
        this.$router.push({
            name:detail,
            pramas:{
                id:index
            }
        })
        
    • 自组件获取参数 this.$router.prams
  • 路由历史记录this.push 路径是放入栈里 this.$router.go(-1) -1是上一个,+1是下一个。

  • 404界面,匹配路由找不到

    {path:'*',compoent:NotFound}
    
  • 多组件界面

    • 一个界面多个占位路由,再main.js界面一个路由对象的components有多个组件
      • key:value key 是对应试图的name属性, value是要显示的组件对象
      routes: [{
              path: '/',
              components: {
                  header: footer,
                  default: header,
                  footer: footer
                  }
              }
      
    • 在入口页写三个router-view 没有namedefault
    <!-- 留坑,非常重要 坑名-->
    <router-view class="b" name="header"></router-view>
    <router-view class="b" ></router-view>
    <router-view class="b" name="footer"></router-view>
    

7.vue-router

  • 前端路由 核心就是锚点值的改变,根据不同的值,渲染指定DOM位置的不同数据
  • ui-router:锚点值改变,如何获取模板?ajax、
  • vue中,模板数据不是通过ajax请求来,而是调用函数获取到模板内容
  • 核心:锚点值改变
  • 以后看到vue开头,就知道必须Vue.use
  • vue的核心插件:
    • vue-router 路由
    • vuex 管理全局共享数据
  • 使用方式
    • 1:下载 npm i vue-router -S
    • 2:在main.js中引入 import VueRouter from 'vue-router';
    • 3:安装插件 Vue.use(VueRouter);
    • 4:创建路由对象并配置路由规则
      • let router = new VueRouter({ routes:[ {path:'/home',component:Home} ] });
    • 5:将其路由对象传递给Vue的实例,options中
      • options中加入 router:router
    • 6:在app.vue中留坑 <router-view></router-view>

8.命名路由

  • 需求,通过a标签点击,做页面数据的跳转
  • 使用router-link标签
    • 1:去哪里 <router-link to="/beijing">去北京</router-link>
    • 2:去哪里 <router-link :to="{name:'bj'}">去北京</router-link>
      • 更利于维护,如果修改了path,只修改路由配置中的path,该a标签会根据修改后的值生成href属性

9.参数router-link

  • 在vue-router中,有两大对象被挂载到了实例this
  • route(只读、具备信息的对象)、router(具备功能函数)
  • 查询字符串
    • 1:去哪里 <router-link :to="{name:'detail',query:{id:1} } ">xxx</router-link>
    • 2:导航(查询字符串path不用改) { name:'detail' , path:'/detail',组件}
    • 3:去了干嘛,获取路由参数(要注意是query还是params和对应id名)
      • this.$route.query.id
  • path方式
    • 1:去哪里 <router-link :to="{name:'detail',params:{name:1} } ">xxx</router-link>
    • 2:导航(path方式需要在路由规则上加上/:xxx)
    • { name:'detail' , path:'/detail/:name',组件}
    • 3:去了干嘛,获取路由参数(要注意是query还是params和对应name名)
      • this.$route.params.name

10.嵌套路由

  • 用单页实线多页应用,复杂的嵌套路由 试图中包含试图,点击能切换部分View,可以结合路由使用
  • 路由包含路由父子关系
  • 初始化VueRouter({})
    • 第一个路由对象 app.vue 默认的启动路由,<router-view></router-view>
      {
        path: '/',
        redirect: { name: 'music' },
      },
      
    • 第二个路由对象 有两个子路由 childern
      • pathshi
      {
          name: 'music',
          path: '/music',
          component: Music,
          children: [
              //-> 这里很灵活,如果你写上/xxx  就是绝对路径, /oumei
              //如果你不写/  ,那么就是相对路径 /music/oumei
              { name: 'music_oumei', path: 'oumei', component: Oumei },
              //name标识一下,当前路由之间的关系,格式不是必须的
              { name: 'music_guochan', path: 'guochan', component: Guochan }
          ]
      }
      

11 VueResource 网络请求

  • npm install vue-resource
  • 引入 import VueResource from 'vue-resource'
  • Vue挂载属性 Vue.use(VueResouce) 通过 this.$http使用
  • 使用代码 网络请求
this.$http.post('urlstring',{},{}).then(res=>{},errr=>{})
post中第一个参数URL,第二个是post传的参数,第三个参数是配置项类似`emulateJSON:true`

12 Axios 网络请求

  • npm install axios
  • 挂在属性 Vue.prototype.$axios = Axios
  • get请求
    • this.$axios.get(url,options)
    • get() 第一个参数URL,第二个参数发送的参数,第三个可以设置baseUrl其他选项
      this.$axios.get('url',{pramas:{},baseURL:'https"//'}).then(res=>{}).catch(error=>{})
      
  • post请求
    • this.$axios.post(url,data,options)
    • post() 第一个参数是URL,第二个{} 中的请求的参数健值对,第三个是请求的设置项 {heasers:{}}
    this.$axios.post('url',{},{headers:{}}).then(res=>{}).catch(error=>{})