Vue基础学习之---基础知识学习笔记

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/feifuzeng/article/details/81284304

该笔记为在跟踪视频学习记录的一套随课笔记,比较乱,但还是有助于了解vue的一些基础知识。

# Vue入门基础
1、绑定属性
v-html   绑定html
v-bind:class 绑定属性
v-bind:style 绑定样式
2、数据双向绑定
双向数据绑定 MVVM vue就是一个MVVM的框架
  M mndel
  V view
  MVVM model改变会影响视图view,view视图改变反过来影响model
  双向数据绑定必须在表单里面使用
3、绑定属性和方法的两种写法
<!--   绑定属性的两种写法
 <img v-bind:src='url'/>
 <img :src=' url'/>
<!--绑定方法的两种写法-->
  <button v-on:click="run()">执行方法的第一种写法</button>
  <button @click="run()">执行方法的第二个方法</button>
4、生命周期函数
      ,beforeCreate(){
          console.log('示例创建之前1')
      },created(){
        console.log('示例创建完成2')
      },beforeMount(){
        console.log('模板编译之前3')
      },mounted(){/* 请求数据、操作dom 放在这个里面  必须记住mounted vue页面刷新就会触发的方法*/
        console.log('模板编译完成4')
      },beforeUpdate(){
        console.log('数据更新之前5')
      },updated(){
        console.log('数据更新完毕6')
      },beforeDestroy(){/* 页面销毁的时候要保存一些数据,就可以监听这个销毁的生命周期函数*/
        console.log('数据销毁之前7')
      },destroyed(){
        console.log('数据销毁完毕8')
      }
5、Vue中单组件被引用以及使用
<template>
  <!--vue的模板里面 所有的内容要被一个根节点包含起来-->
  <div id="app">
  {{msg}}
    <h2>我是引用home的一个组件</h2>
    <v-home></v-home>
  </div>
</template>
<script>
  /*
  * 1、引入组件
  * 2、挂载组件
  * 3、在模板中使用
  * */
  import Home from './components/Home.vue';
export default {
  name: 'app',
  data () {/* 业务逻辑里面定义的数据 */
    return {
      msg: '你好,VUE'
    }
  },components: {/* 前面的组件名不可以跟html标签相同*/
    'v-home':Home
  }
}
</script>
<style lang="scss">
</style>
6、vue-resource请求数据
安装并引入vue-resource
getData(){
        //请求数据
          var apiUrl='http://www.neepp.net/rest/service/routing/nouser/SelectRoleByUserIdBusiService?userId=1';
          this.$http.get(apiUrl).then(response =>{
            console.log(response)
            //注意this指向
            this.list=response.body.data.listBO;
          },response =>{
            console.error(response)
          })
      }
7、jsonp请求数据
  requestData(aid){
            //get请求如果跨域的话,后台php java里面要允许跨域请求
            var api ='http://www.phonegap100.com/appapi.php?a=getPortalArticle&aid='+aid;
            this.$http.get(api).then((response)=>{
              console.log(response)
              this.list=response.body.result[0];
            },(err)=>{
              console.log(err)
            })
          }
8、axios请求数据
    axios 的使用
    1、安装:
       npm install axios --save
    2、哪里用哪里引用axios
       import axios from 'axios'
    fetch-jsonp  用法跟axios差不多

    import Axios from 'axios'
    export default {

    getData(){
        //请求数据
          var apiUrl='http://www.neepp.net/rest/service/routing/nouser/SelectRoleByUserIdBusiService?userId=1';
          Axios.get(apiUrl).then((response)=>{
            console.log(response)
            this.list=response.data.data.listBO;
          }).catch((response => {
            console.error(response)
          }))
      }
9、封装storage组件实现保存本地记录【类似于java后台中session】
  1).封装并暴露storage
  var storage={
    set(key,value){
      localStorage.setItem(key,JSON.stringify(value));
    },
    get(key){
      return JSON.parse(localStorage.getItem(key));
    },
    remove(key){
      localStorage.removeItem(key);
    }
  }
  export default storage;
  2).组件引入并使用
  引入:
  <script>
    import storage from './model/storage.js';
  export default {
  使用:
  在方法或周期函数中
  storage.set('list',this.list);
  var list = storage.get('list');
10、使用props进行父子组件间传值
  父组件给子组件传值(Home父组件调用Header子组件)
     - 1、父组件在调用子组件时绑定动态属性
     <v-header :title="title"></v-header>
     - 2、在子组件里面通过props接受父组件传过来的数据
     ,props:{
            'title':String
        }
    更多有关props:https://cn.vuejs.org/v2/guide/components-props.html
11、父子组件之间主动获取数据
  父组件主动获取子组件的数据和方法
     1).调用子组件的时候定义一个ref
     <v-header ref='header'></v-header>
     2).在父组件里面通过
      this.$refs.header.属性
     this.$refs.header.方法
     子组件主动获取父组件的数据和方法:
     this.$parent.数据
     this.$parent.方法
12、非父子组件间传值
  1).新建一个js文件,引入vue,实例化vue并暴露
  vueEvent.js
  import Vue from 'vue';
  var VueEvent = new Vue()
  export default VueEvent;
  2).在要广播的地方引入刚才定义的实例[传递数据方和接受数据方都需要进行引入]
  <script>
    import VueEvent from '../model/vueEvent.js';
      export default {
  3).通过VueEmit.$emit('名称','数据')传递数据
  ,methods:{
      emitHome(){
        VueEvent.$emit('to-home',this.msg);
      }
  4).在接收数据的地方通过$on接受广播的数据VueEmit.$on('名称',function(){})
  ,mounted(){
        VueEvent.$on('to-home',function (data) {
          console.log(data)
        })
    }
13、Vue中路由配置
  官网:https://router.vuejs.org/
  vue路由配置:
      1).安装
      npm install vue-router  --save   / cnpm install vue-router  --save
      2)、引入并 Vue.use(VueRouter)   (main.js)
          import VueRouter from 'vue-router'
          Vue.use(VueRouter)
      3)、配置路由
          1、创建组件 引入组件
          2、定义路由  (建议复制s)
              const routes = [
                { path: '/foo', component: Foo },
                { path: '/bar', component: Bar },
                { path: '*', redirect: '/home' }   /*默认跳转路由*/
              ]
          4)、实例化VueRouter
              const router = new VueRouter({
                routes // (缩写)相当于 routes: routes
              })
          5)、挂载
          new Vue({
            el: '#app',
            router,
            render: h => h(App)
          })
          6)、根组件的模板里面放上这句话
      <router-view></router-view>
          7)、路由跳转
          <router-link to="/foo">Go to Foo</router-link>
          <router-link to="/bar">Go to Bar</router-link>
14、不同路由间传值
  1)、不同路由传值:动态路由
   * 1.配置动态路由
   * routes: [
     // 动态路径参数 以冒号开头
     { path: '/user/:id', component: User }
   ]
   * 2.在调用组件方
   <router-link :to="'/pcontent?id='+key">{{key}}---{{item}}</router-link>
   * 3.在被调用组件方对应页面
   this.$route.params获取动态路由的值
   2)、不同路由传值:get传值
   * 1.配置动态路由
   * routes: [
   { path: '/user', component: User }
   ]
   * 2.在调用方组件
   <router-link :to="'/content/'+item.aid">{{key}}---{{item.title}}</router-link>
   * 3.在被调用方对应页面
   this.$route.query获取get请求传的值
15、通过js跳转跳转页面
  ,methods:{
      goNews(){
        //注意:官方文档写错了
        //第一种跳转方式
        // this.$router.push({path:'content/495'});
        // this.$router.push({name:'news',params:{userId:123}})
        // 另一种跳转方式
        this.$router.push({name:'news'})
      }
    }
16、路由的嵌套
  * 1.配置路由
  const routes = [
    { path: '/home', component: Home },
    { path: '/news', component: News,name:'news' },
    { path: '/content/:aid', component: Content },/**动态路由*/
    { path: '/pcontent', component: Pcontent },
    {
      path: '/user',
      component: User,
      children:[
        { path: 'useradd', component: UserAdd },
        { path: 'userlist', component: UserList },
      ]
    },
    { path:'*',redirect:'/home'}/* 默认跳转路由 */
  ]
  *2 在父组件User中引入子组件
  <template>
    <!--html代码-->
    <div id="user">
    <div class="user">
        <div class="left">
          <ul>
            <li>
              <router-link to="/user/useradd">增加用户</router-link>
            </li>
            <li>
              <router-link to="/user/userlist">用户列表</router-link>
            </li>
          </ul>
        </div>
        <div class="right">
          <router-view></router-view>
        </div>
    </div>
    </div>
  </template>
17、Vue中mintUI介绍
  基于Vue的Ui框架
      饿了么公司基于vue开的的vue的Ui组件库
          Element Ui    基于vue  pc端的UI框架
          MintUi         基于vue 移动端的ui框架
  http://element.eleme.io/
  http://mint-ui.github.io/#!/en
  mintUI的使用:
      1.找官网
      2.安装   npm install mint-ui -S         -S表示  --save
      3.引入mint Ui的css 和 插件
          import Mint from 'mint-ui';
          Vue.use(Mint);
          import 'mint-ui/lib/style.css'
      4.看文档直接使用。
  在mintUi组件上面执行事件的写法
  @click.native
  <mt-button @click.native="sheetVisible = true" size="large">点击上拉 action sheet</mt-button>
18、Vue中ElementUI使用
  基于Vue的Ui框架
      饿了么公司基于vue开的的vue的Ui组件库
          Element Ui    基于vue  pc端的UI框架
          MintUi         基于vue 移动端的ui框架
  http://element.eleme.io/
  element UI的使用:
      1.找官网  http://element.eleme.io/#/zh-CN/component/quickstart
      2.安装  cnpm i element-ui -S         -S表示  --save
      3.引入element UI的css 和 插件
          import ElementUI from 'element-ui';
          import 'element-ui/lib/theme-chalk/index.css';
          Vue.use(ElementUI);
      4、*webpack.config.js  配置file_loader      http://element.eleme.io/1.4/#/zh-CN/component/quickstart
            {
              test: /\.(eot|svg|ttf|woff|woff2)(\?\S*)?$/,
              loader: 'file-loader'
                }
      5.看文档直接使用。
  element UI组件的单独使用(第一种方法):
      1、cnpm install babel-plugin-component -D
      2、找到.babelrc 配置文件
          把
          {
            "presets": [
              ["env", { "modules": false }],
              "stage-3"
            ]
          }
          改为  注意:
          {
            "presets": [["env", { "modules": false }]],
            "plugins": [
              [
                "component",
                {
              "libraryName": "element-ui",
              "styleLibraryName": "theme-chalk"
                }
              ]
            ]
          }
      3、
      import { Button, Select } from 'element-ui';
      Vue.use(Button)
      Vue.use(Select)
  element UI组件的单独使用(第二种方法):
      import { Button, Select } from 'element-ui';
      Vue.use(Button)
      Vue.use(Select)
      引入对应的css
          import 'element-ui/lib/theme-chalk/index.css';
      如果报错: webpack.config.js  配置file_loader
            {
              test: /\.(eot|svg|ttf|woff|woff2)(\?\S*)?$/,
              loader: 'file-loader'
                }
19、Vuex状态管理
  Vuex 是一个专为 Vue.js 设计的状态管理模式
  vuex解决了组件之间同一状态的共享问题。当我们的应用遇到多个组件共享状态时,会需要:
  多个组件依赖于同一状态。传参的方法对于多层嵌套的组件将会非常繁琐,并且对于兄弟组件间的状态传递无能为力。这需要你去学习下,vue编码中多个组件之间的通讯的做法。
  来自不同组件的行为需要变更同一状态。我们经常会采用父子组件直接引用或者通过事件来变更和同步状态的多份拷贝。
  以上的这些模式非常脆弱,通常会导致无法维护的代码。来自官网的一句话:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。
  它采用集中式存储管理应用的所有组件的状态。这里的关键在于集中式存储管理。这意味着本来需要共享状态的更新是需要组件之间通讯的,而现在有了vuex,就组件就都和store通讯了。问题就自然解决了。
  这就是为什么官网再次会提到Vuex构建大型应用的价值。如果您不打算开发大型单页应用,使用 Vuex 可能是繁琐冗余的。确实是如此——如果您的应用够简单,您最好不要使用 Vuex。
  Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式
    1.vuex解决了组件之间同一状态的共享问题  (解决了不同组件之间的数据共享)
    2.组件里面数据的持久化。
  小项目不部建议用vuex
  vuex的使用:
  1、src目录下面新建一个vuex的文件夹
  2、vuex 文件夹里面新建一个store.js
  3、安装vuex
    cnpm install vuex --save
  4、在刚才创建的store.js引入vue  引入vuex 并且use vuex
    import Vue from 'vue'
    import Vuex from 'vuex'
    Vue.use(Vuex)
  5、定义数据
      /*1.state在vuex中用于存储数据*/
      var state={
          count:1
      }
  6、定义方法     mutations里面放的是方法,方法主要用于改变state里面的数据
    var mutations={
        incCount(){
      ++state.count;
        }
    }
  7、优点类似计算属性   ,  改变state里面的count数据的时候会触发 getters里面的方法 获取新的值 (基本用不到)
    var getters= {
      computedCount: (state) => {
      return state.count*2
        }
    }
  8、 Action 基本没有用
    Action 类似于 mutation,不同在于:
    Action 提交的是 mutation,而不是直接变更状态。
    Action 可以包含任意异步操作。
    var actions= {
        incMutationsCount(context) {    /*因此你可以调用 context.commit 提交一个 mutation*/
      context.commit('incCount');    /*执行 mutations 里面的incCount方法 改变state里面的数据*/
        }
    }
  暴露
    const store = new Vuex.Store({
        state,
        mutations,
        getters,
        actions
    })
    export default store;
  组建里面使用vuex:
    1.引入 store
       import store from '../vuex/store.js';
    2、注册
       export default{
        data(){
            return {
               msg:'我是一个home组件',
          value1: null,
            }
        },
        store,
        methods:{
            incCount(){
          this.$store.commit('incCount');   /*触发 state里面的数据*/
            }
        }
          }
    3、获取state里面的数据
      this.$store.state.数据
    4、触发 mutations 改变 state里面的数据
      this.$store.commit('incCount');
    5、触发 actions里面的方法
      this.$store.dispatch('incCount');
    6、{{this.$store.getters.computedCount}}  获取 getters里面方法返回的的数据

猜你喜欢

转载自blog.csdn.net/feifuzeng/article/details/81284304