Vue框架快速上手

发布时间 2023-10-02 14:46:40作者: yetangjian

Vue基础

vue指令

内容绑定

v-text

设置标签的内容一般通过双大括号的表达式{{ }}去替换内容

{{ hello }}

v-html

与v-text类似区别在于html中的结构会被解析为标签设置元素的innerHTML,v-text只会解析文本

事件绑定

v-on

可以简写为@,绑定的方法在methods中

显示切换

v-show

原理是修改的元素的display实现隐藏,指令后的内容最终都会解析为布尔值

v-if

可以搭配v-else-if v-else使用

通过表达式来确认是否从dom树中删除

<body>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <div id="app">
        <button v-show="imgNum != '0'" @click="changeNum">上一张</button>
        <img :src="imgNum+'.jpg'" alt="" class="picSize">
        <button>下一张</button>
    </div>

    <script>
        var app = new Vue({
            el:"#app",
            data:{
                imgNum:"1"
            },
            methods:{
                changeNum: function(){
                    let n = parseInt(this.imgNum);
                    n++;
                    n %= 3;
                    this.imgNum = n.toString();
                }
            }
        })
    </script>
</body>

属性绑定

v-bind

可以通过简写:属性名来绑定属性

列表循环

v-for

通常搭配数组一起使用,语法(item,index) in 数据

        <ul>
            <li v-for="(item,index) in noteHistory">
                {{ item }} <span v-show="item?true:false" @click="deleteHistory(index)">x</span>
            </li>
        </ul>

双向数据绑定

v-model

绑定数据和表单元素相关联

<body>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
    <div id="app">
        <input type="text" v-model="message" @keyup.enter="updateList">
        <ul>
            <li v-for="(item,index) in noteHistory">
                {{ item }} <span v-show="item?true:false" @click="deleteHistory(index)">x</span>
            </li>
        </ul>
        <span v-show="noteHistory.length > 0 ">总条数:<strong> {{ noteHistory.length }} </strong> </span>
        <button @click="clear" v-show="noteHistory.length > 0 ">清空</button>
    </div>

    <script>
        var app = new Vue({
            el:"#app",
            data:{
                noteHistory:[],
                message: ""
            },
            methods:{
                updateList: function(){
                    this.noteHistory.push(this.message);
                    // 新增后清空message
                    this.message = "";
                },
                deleteHistory: function(index){
                    this.noteHistory.splice(index,1);
                },
                clear: function(){
                    this.noteHistory = [];
                }
            }
        })
    </script>
</body>

前期安装

  1. 我们的框架需要通过NPM来管理我们的NodeJs的包
    • 下载地址 https://nodejs.org/en 选择稳定版本
  2. Vue CLi是vue的脚手架,我们通过命令npm install -g@vue/cli创建一个项目vue create + 项目名称
  3. package.json所有的依赖包都在这里,我们可以通过npm install 安装
    • 通过npm run serve运行

组件开发

  1. 组件后缀名都是.vue
  2. 每个组件基本有三部分组成template标签中是组件的结构,script放入组件js代码,style是组件的样式代码
<template>
    <div>
        <h1>{{ question }}</h1>
    </div>
</template>
<script>
    export default{
        name:"movie",
        data:function(){
            return {
                question:"显示问题"
            }
        }
    }
</script>

父组件传值props两种方法一种通过路由对象获取

第二种方法,需要在main.js中routes设置属性props:true,组件中在定义属性名称

//动态路由
[{path:'song/:id',component: Song, props:true}]
<template>
    <div>
        <!-- 第一种方法获取路由中的id-->
        <h6>{{ $route.params.id }}</h6>
        <!-- 第二种办法是设置props-->
        <h6>{{ id }}</h6>
    </div>
    
</template>

<script>
    export default({
        props:['id']
    })
</script>

element.ui

安装npm i element-ui -s

方便使用我们可以在main.js里面全局import ElementUI from 'element-ui'

Axios:前端页面向服务器发起请求

安装

npm install axios

在项目的main.js中导入,同时设置请求baseUrl

import axios from 'axios'
axios.defaults.baseURL = "http://127.0.0.1:5000"
Vue.prototype.$http = axios

发送网络请求

第一个then后面跟着处理成功的情况,catch用来处理失败的情况,最后一个then总是会执行的。

get请求

axios.get(uri,{params:{ }}).then(function(response)){ }.catch(function(error){ }).then(function(){ })

post请求

axios.post(uri,{ }).then(function(response)){ }.catch(function(error){ })

在需要使用的网络请求的地方使用

export default {
  name: 'App',
  data(){
    return {
      name: "",
      age: 0
    }
  },
  components: {
    HelloWorld,
    movie
  },
  //网络请求一般在created里面做,在挂载的时候做
  created:function(){
    this.$http.post("/index",{"name":"Jack","age":30})
    .then((response)=>{
      console.log(response.data.name);
      this.name = response.data.name;
      this.age = response.data.age;
    })
    .catch((error)=>{
      console.log(error.data.name);
      console.log(error);
    })
  }
}

mockjs

npm install mockjs

在项目创建mock目录,新建index.js文件

//引入mock.js
import Mock from 'mockjs'
//使用mockjs
Mock.mock(RegExp('/index'),{"name":"MOCK","age":30})

在项目中main.js中导入就可以了,如果不想用了直接删掉main.js中导入的包即可

import './mock'

VueRouter

这是官方的路由组件,用来管理单页面的路由和组件的映射

安装npm install vue-router@3 (vue2)npm install vue-router@4 (vue3)

在需要管理的组件(.Vue)中做路由链接,需要使用路由站位标签

<template>
    <div>
        <h1>我的音乐</h1>
        <!-- 声明路由链接-->
        <router-link to="/my/song/1">歌曲1</router-link>
        <router-link to="/my/song/2">歌曲2</router-link>
        <router-link to="/my/song/3">歌曲3</router-link>
        <!-- 路由需要站位标签-->
        <router-view></router-view>
    </div>
</template>

新建一个文件router,在文件下新建一个index.js

通过routes来控制路由和组件的映射:重定向、路由嵌套、动态路由

import VueRouter from "vue-router";
import Vue from "vue";
//把需要的组件导入进来
import Discover from '../components/Discover'
import Friend from '../components/Friend'
import My from '../components/My'
import Music from '../components/Music'
import Song from '../components/Song'
//将vuerouter注册为vue的插件
Vue.use(VueRouter)
// 执行属性与组件的对应关系
const router = new VueRouter({
    routes:[
        //首页重定向
        {path:'/',redirect: Discover},
        {path:'/discover',component: Discover,
        //通过children来声明子路由,做路由嵌套/discover/music
        children:[
            {path:'music',component: Music}
        ]
    },
        {path:'/friend',component: Friend},
        {path:'/my',component: My,children:
        //动态路由
        [{path:'song/:id',component: Song, props:true}]
        }
    ]
})
//需要做一个导出
export default router

在项目的main.js中导入并且在Vue中添加上这个router

import router from './router'
Vue.config.productionTip = false
new Vue({
  render: h => h(App),
  //key和value名字一直可以就写一个key
  router
}).$mount('#app')