首页 > 其他分享 >Vue学习笔记Day01

Vue学习笔记Day01

时间:2024-03-28 18:34:34浏览次数:23  
标签:axios name vue Day01 笔记 js Vue import data

软件安装:
node.js
vscode
一、基于脚手架创建前端工程

(一)环境要求:

1.node.js:前端项目的运行环境;(查看版本号:node -v
2.npm: JavaScript的包管理工具;(查看版本号:npm -v
3.Vue CLI:基于Vue进行快速开发的完整系统,实现交互式的项目脚手架。 (安装Vue CLI:npm i @vue/cli -g)

(二)使用Vue CLI创建前端工程:

1.vue create 项目名称
2.vue ui

(三)不使用Vue CLI创建Vue项目使用命令:npm init vue@latest

(四)项目结构

node_modules:当前项目依赖的js包;
assets:静态资源存放目录;
components:公共组件存放目录;
App.vue:项目的主组件,页面的入口文件;
main.js:整个项目的入口文件;
package.json:项目的配置信息、依赖包管理;
vue.config.js:vue-cli配置文件。

(五)启动项目

npm run serve(Ctrl+C:终止)

(六)修改前端服务的端口号

在vue.config.js文件中配置前端服务端口号:
const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ transpileDependencies: true, devServer:{ port: XXXX } })

二、vue基本使用方法

(一)vue组件

以.vue结尾,每个组件由三部分组成:
1.结构 < template >
只有一个根元素;由它生成HTML代码
2.样式 < style >
编写css,控制页面展示效果;全局样式:影响所有组件;局部样式:只作用于当前组件
3.逻辑 < script >
编写js代码;控制模板的数据来源和行为

(二)文本插值
作用:用来绑定data方法返回的对象属性
用法:{{}}

(三)属性绑定
作用:为标签的属性绑定data方法返回的属性
用法:v-bind:xxx,简写为:xxx

(四)事件绑定
作用:为元素绑定对应事件
用法:v-on:xxx,简写为@xxx

(五)双向绑定
作用:表单输入项和data方法中的属性进行绑定,任意一方改变都会同步给另一方
用法:v-model

(六)条件渲染
作用:根据表达式的值来动态渲染页面元素
用法:v-if、v-else、v-else-if

(七)axios
Axios是一个基于promise的网路数据库,作用于浏览器和node.js中
安装命令:npm install axios
导入命令:import axios from 'axios'

axios的API列表:
请求
axios.get(url[,config])
axios.delete(url[,config])
axios.head(url[,config])
axios.options(url[,config])
axios.post(url[,data[,config]])
axios.put(url[,data[,config]])
axios.patch(url[,data[,config]])

参数说明:
url:请求路径
data:请求体数据,最常见的是JSON格式数据
config:配置对象,可以设置查询参数、请求头信息

点击查看代码
<template>
  <div class="hello">
    <!-- 文本插值 -->
    {{ name }}
    {{ age > 60 ? '老年' : '青年' }}

    <!-- 属性绑定 -->
    <div><input type="text" v-bind:value="name"></div>
    <div><input type="text" :value="age"></div>
    <div><img :src='src'/></div>

    <!-- 事件绑定 -->
    <input type="button" value="保存" v-on:click="handSave"/>
    <input type="button" value="保存" @click="handSave"/>
    
    <!-- 双向绑定 -->
    <input type="text" v-model="name"/>
    <input type="button" value="修改name的值 " @click="handChange"/>
  
    <!-- 条件渲染 -->
    <div v-if="sex == 1">男</div>
    <div v-else-if="sex == 2">女</div>
    <div v-else>未知</div>

    <input type="button" value="发送请求" @click="handSend"/>
  </div>
</template>

<script>
// 导入
import axios from 'axios'

export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data(){
    return {
      name: '张三',
      age: 30,
      src:'https://p1.ssl.qhmsg.com/dr/270_500_/t0181185146f5273660.jpg',
      sex:1
    }
  },
  methods:{
    handSave(){
      alert('已成功保存')
    },
    handChange(){
      this.name='李四'
    },
    handSend(){
      // 通过axios发送http请求
        axios.post('http://localhost:8080/admin/employee/login',{
        username:'admin',
        password:'123456'
      }).then(res => {
        console.log(res.data)
      }).catch(error => {
        console.log(error.response)
      })
    }
  }
}
</script>

No 'Access-Control-Allow-Origin'表示出现跨域问题,为了解决跨域问题,可以再vue.config.js文件中配置代理:

点击查看代码
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer:{
    port:7070,
    // 配置前端代理
    proxy: {
      '/api': {
        target:'http://localhost:8080',
        pathRewrite: { //路径重写
          '^/api': ''
        }
      }
    }
  }
})

点击查看代码
<template>
  <div class="hello">
    <!-- 文本插值 -->
    {{ name }}
    {{ age > 60 ? '老年' : '青年' }}

    <!-- 属性绑定 -->
    <div><input type="text" v-bind:value="name"></div>
    <div><input type="text" :value="age"></div>
    <div><img :src='src'/></div>

    <!-- 事件绑定 -->
    <input type="button" value="保存" v-on:click="handSave"/>
    <input type="button" value="保存" @click="handSave"/>
    
    <!-- 双向绑定 -->
    <input type="text" v-model="name"/>
    <input type="button" value="修改name的值 " @click="handChange"/>
  
    <!-- 条件渲染 -->
    <div v-if="sex == 1">男</div>
    <div v-else-if="sex == 2">女</div>
    <div v-else>未知</div>

    <input type="button" value="发送请求" @click="handSend"/>
  </div>
</template>

<script>
// 导入
import axios from 'axios'

export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data(){
    return {
      name: '张三',
      age: 30,
      src:'https://p1.ssl.qhmsg.com/dr/270_500_/t0181185146f5273660.jpg',
      sex:1
    }
  },
  methods:{
    handSave(){
      alert('已成功保存')
    },
    handChange(){
      this.name='李四'
    },
    handSend(){
      // 通过axios发送http请求
        axios.post('/api/admin/employee/login',{
        username:'admin',
        password:'123456'
      }).then(res => {
        console.log(res.data)
      }).catch(error => {
        console.log(error.response)
      })
    }
  }
}
</script>

发送get请求时校验失败,返回401,需要令牌token

点击查看代码
<template>
  <div class="hello">
    <!-- 文本插值 -->
    {{ name }}
    {{ age > 60 ? '老年' : '青年' }}

    <!-- 属性绑定 -->
    <div><input type="text" v-bind:value="name"></div>
    <div><input type="text" :value="age"></div>
    <div><img :src='src'/></div>

    <!-- 事件绑定 -->
    <input type="button" value="保存" v-on:click="handSave"/>
    <input type="button" value="保存" @click="handSave"/>
    
    <!-- 双向绑定 -->
    <input type="text" v-model="name"/>
    <input type="button" value="修改name的值 " @click="handChange"/>
  
    <!-- 条件渲染 -->
    <div v-if="sex == 1">男</div>
    <div v-else-if="sex == 2">女</div>
    <div v-else>未知</div>

    <input type="button" value="发送POST请求" @click="handSendPOST"/>
    <input type="button" value="发送GET请求" @click="handSendGET"/>
  </div>
</template>

<script>
// 导入
import axios from 'axios'

export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data(){
    return {
      name: '张三',
      age: 30,
      src:'https://p1.ssl.qhmsg.com/dr/270_500_/t0181185146f5273660.jpg',
      sex:1
    }
  },
  methods:{
    handSave(){
      alert('已成功保存')
    },
    handChange(){
      this.name='李四'
    },
    handSendPOST(){
      // 通过axios发送post请求
      // axios.post('http://localhost:8080/admin/employee/login',{
        axios.post('/api/admin/employee/login',{
        username:'admin',
        password:'123456'
      }).then(res => {
        console.log(res.data)
      }).catch(error => {
        console.log(error.response)
      })
    },
    handSendGET(){
      // 通过axios发送get请求
      axios.get('/api/admin/shop/status').then(res => {
        console.log(res.data)
      })
    }
  }
}
</script>

可通过发送post请求的结果获取token值

点击查看代码
handSendGET(){
      // 通过axios发送get请求
      axios.get('/api/admin/shop/status',{
        //请求头信息
        headers: {
          token: 'xxxxxxxxxx' //具体token值
        }
      }).then(res => {
        console.log(res.data)
      })
    }

axios统一使用方式:axios(config)
https://www.axios-http.cn/docs/req_config

点击查看代码
<template>
  <div class="hello">
    <!-- 文本插值 -->
    {{ name }}
    {{ age > 60 ? '老年' : '青年' }}

    <!-- 属性绑定 -->
    <div><input type="text" v-bind:value="name"></div>
    <div><input type="text" :value="age"></div>
    <div><img :src='src'/></div>

    <!-- 事件绑定 -->
    <input type="button" value="保存" v-on:click="handSave"/>
    <input type="button" value="保存" @click="handSave"/>
    
    <!-- 双向绑定 -->
    <input type="text" v-model="name"/>
    <input type="button" value="修改name的值 " @click="handChange"/>
  
    <!-- 条件渲染 -->
    <div v-if="sex == 1">男</div>
    <div v-else-if="sex == 2">女</div>
    <div v-else>未知</div>

    <input type="button" value="发送POST请求" @click="handSendPOST"/>
    <input type="button" value="发送GET请求" @click="handSendGET"/>
    <input type="button" value="统一请求方式" @click="handSend"/>
  </div>
</template>

<script>
// 导入
import axios from 'axios'

export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data(){
    return {
      name: '张三',
      age: 30,
      src:'https://p1.ssl.qhmsg.com/dr/270_500_/t0181185146f5273660.jpg',
      sex:1
    }
  },
  methods:{
    handSave(){
      alert('已成功保存')
    },
    handChange(){
      this.name='李四'
    },
    handSendPOST(){
      // 通过axios发送post请求
      // axios.post('http://localhost:8080/admin/employee/login',{
        axios.post('/api/admin/employee/login',{
        username:'admin',
        password:'123456'
      }).then(res => {
        console.log(res.data)
      }).catch(error => {
        console.log(error.response)
      })
    },
    handSendGET(){
      // 通过axios发送get请求
      axios.get('/api/admin/shop/status',{
        //请求头信息
        headers: {
          token: 'xxxxxxxxxx' //对应token值
        }
      }).then(res => {
        console.log(res.data)
      })
    },
    handSend(){
      //使用axios提供的统一调用方式发送请求
      axios({
        url: '/api/admin/employee/login',
        method: 'post',
        data: { //data表示通过请求体传参
          username: 'admin',
          password: '123456'
        }
      }).then(res => {
        // 打印token
        // console.log(res.data.data.token)
        axios({
          url: '/api/admin/shop/status',
          method: 'get',
          headers: {
            token: res.data.data.token
          }
        })
      })
    }
  }
}
</script>

三、路由Vue-Router

(一)Vue-Router介绍

vue属于单页面应用,所谓的路由,就是根据浏览器路径不同,用不同的视图组件替换这个页面内容

基于Vue CLI创建带有路由功能的前端项目:
命令:vue ui

通过vue-router实现路由功能,需要安装js库(npm install vue-router

(二)路由配置

1.路由组成:
(1)VueRouter:路由器,根据路由请求在路由视图中动态渲染对应的视图组件;
(2)< router-link >:路由连接组件,浏览器会解析成< a >;
(3)< router-view >:路由视图组件,用来展示与路由路径匹配的视图组件。

index.js

点击查看代码
import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'

Vue.use(VueRouter)

//维护路由表,某个路由路径对应哪个视图组件
const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView //静态导入,打包到同一个js文件中
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue') //懒加载,单独打包到一个js文件中
  }
]

const router = new VueRouter({
  routes
})

export default router

App.vue

点击查看代码
<template>
  <div id="app">
    <nav>
      <!-- 指定路由路径 -->
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link> 
    </nav>
    <!-- 视图组件展示的位置 -->
    <router-view/>
  </div>
</template>

2.路由跳转

(1)标签式
通过router-link
(2)编程式

点击查看代码
<template>
  <div id="app">
    <nav>
      <!-- 指定路由路径 -->
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link> |
      <input type="button" value="编程式路由跳转" @click="jump"/>
    </nav>
    <!-- 视图组件展示的位置 -->
    <router-view/>
  </div>
</template>

<script>
export default {
  methods: {
    jump() {
      //使用编程式路由跳转方式
      /* this.$router是获取到路由对象
      push方法是根据url进行跳转 */
      this.$router.push('/about')
    }
  },
}
</script>

当用户访问的路由地址不存在时,重定向为404
App.vue

点击查看代码
<template>
  <div id="app">
    <nav>
      <!-- 指定路由路径 -->
      <router-link to="/">Home</router-link> |
      <router-link to="/about">About</router-link> |
      <!-- 不存在的页面 -->
      <router-link to="/test">Test</router-link> |  
      <input type="button" value="编程式路由跳转" @click="jump"/>
    </nav>
    <!-- 视图组件展示的位置 -->
    <router-view/>
  </div>
</template>

<script>
export default {
  methods: {
    jump() {
      //使用编程式路由跳转方式
      /* this.$router是获取到路由对象
      push方法是根据url进行跳转 */
      this.$router.push('/about')
    }
  },
}
</script>

index.js

点击查看代码
import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'

Vue.use(VueRouter)

//维护路由表,某个路由路径对应哪个视图组件
const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView //静态导入,打包到同一个js文件中
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue') //懒加载,单独打包到一个js文件中
  },
  {
    path: '/404',
    component: () => import('../views/404View.vue')
  },
  {
    path: '*',
    redirect: '/404' //重定向
  }
]

const router = new VueRouter({
  routes
})

export default router

404View.vue

点击查看代码
<template>
  <div class="404">
    <h1>您请求的资源不存在!</h1>
  </div>
</template>

3.嵌套路由

组件内要切换内容,需要用嵌套路由(子路由)

实现步骤:
安装并导入element-ui,实现页面布局(Container布局容器)——ContainerView.vue;

点击查看代码
<template>
    <el-container>
        <el-header>Header</el-header>
        <el-container>
            <el-aside width="200px">Aside</el-aside>
            <el-main>Main</el-main>
        </el-container>
    </el-container>
</template>

<script>
export default {

}
</script>

<style>
    .el-header,
    .el-footer {
        background-color: #B3C0D1;
        color: #333;
        text-align: center;
        line-height: 60px;
    }

    .el-aside {
        background-color: #D3DCE6;
        color: #333;
        text-align: center;
        line-height: 200px;
    }

    .el-main {
        background-color: #E9EEF3;
        color: #333;
        text-align: center;
        line-height: 160px;
    }

    body>.el-container {
        margin-bottom: 40px;
    }

    .el-container:nth-child(5) .el-aside,
    .el-container:nth-child(6) .el-aside {
        line-height: 260px;
    }

    .el-container:nth-child(7) .el-aside {
        line-height: 320px;
    }
</style>

提供子视图组件,用于效果展示——P1View.vue、P2View.vue、P3View.vue;

点击查看代码
<template>
    <div>
        这是P1View
    </div>
</template>

<script>
export default {

}
</script>

<style></style>
点击查看代码
<template>
    <div>
        这是P2View
    </div>
</template>

<script>
export default {

}
</script>

<style></style>
点击查看代码
<template>
    <div>
        这是P3View
    </div>
</template>

<script>
export default {

}
</script>

<style></style>

在src/router/index.js中配置映射规则(嵌套路由设置);

点击查看代码
import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/HomeView.vue'

Vue.use(VueRouter)

//维护路由表,某个路由路径对应哪个视图组件
const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView //静态导入,打包到同一个js文件中
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue') //懒加载,单独打包到一个js文件中
  },
  {
    path: '/404',
    component: () => import('../views/404View.vue')
  },
  {
    path: '/c',
    component: () => import('../views/container/ContainerView.vue'),
    //嵌套路由(子路由),对应的组件会展示在当前组件内部
    children: [
      {
        path: '/c/p1',
        component: ()=> import('../views/container/P1View.vue')
      },{
        path: '/c/p2',
        component: ()=> import('../views/container/P2View.vue')
      },{
        path: '/c/p3',
        component: ()=> import('../views/container/P3View.vue')
      }
    ]
  },
  {
    path: '*',
    redirect: '/404' //重定向
  }
]

const router = new VueRouter({
  routes
})

export default router

在布局容器视图中添加< router-view >,实现子视图组件展示;

点击查看代码
<template>
    <el-container>
        <el-header>Header</el-header>
        <el-container>
            <el-aside width="200px">Aside</el-aside>
            <el-main>
                <router-view/>
            </el-main>
        </el-container>
    </el-container>
</template>

在布局容器视图中添加< router-link >,实现路由请求。

点击查看代码
<template>
    <el-container>
        <el-header>Header</el-header>
        <el-container>
            <el-aside width="200px">
                <!-- <br>是换行 -->
                <router-link to="/c/p1">P1</router-link><br>
                <router-link to="/c/p2">P2</router-link><br>
                <router-link to="/c/p3">P3</router-link><br>
            </el-aside>
            <el-main>
                <router-view/>
            </el-main>
        </el-container>
    </el-container>
</template>

注:子路由变化,切换的是【ContainerView组件】中‘< router-view >< /router-view >’部分的内容。

如果用户直接访问的路径为/c,不会显示子视图组件,可通过重定向设置默认子视图组件。

点击查看代码
{
    path: '/c',
    component: () => import('../views/container/ContainerView.vue'),
    redirect: '/c/p1',
    //嵌套路由(子路由),对应的组件会展示在当前组件内部
    children: [
      {
        path: '/c/p1',
        component: ()=> import('../views/container/P1View.vue')
      },{
        path: '/c/p2',
        component: ()=> import('../views/container/P2View.vue')
      },{
        path: '/c/p3',
        component: ()=> import('../views/container/P3View.vue')
      }
    ]
  },

(三)状态管理vuex

介绍:
vuex是一个专为Vue.js应用程序开发的状态管理库
vuex可以在多个组件之间共享数据,并且共享的数据是响应式的,即数据的变更能及时渲染到模板
vuex采用集中式存储管理所有组件的状态

安装vuex:npm install vuex@next--save

核心概念:
state:状态对象,集中定义各个组件共享的数据
mutations:类似于一个事件,用于修改共享数据,要求必须是同步函数
actions:类似于mutation,可以包含异步操作,通过调用mutation来改变共享数据

使用方式:
创建带有vuex功能的脚手架工程

index.js

点击查看代码
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

//集中管理多个组件共享的数据
export default new Vuex.Store({
  state: {
  },
  getters: {
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  }
})

定义和展示共享数据
index.js

点击查看代码
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

//集中管理多个组件共享的数据
export default new Vuex.Store({
  //集中定义共享数据
  state: {
    name: '未登录游客'
  },
  getters: {
  },
  //修改共享数据只能通过mutation实现,必须是同步操作
  mutations: {
  },
  //通过actions可以调用到mutations,在actions中可以进行异步操作
  actions: {
  },
  modules: {
  }
})

App.vue

点击查看代码
<template>
  <div id="app">
    欢迎你,{{$store.state.name}}
    <img alt="Vue logo" src="./assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
  </div>
</template>

在mutations中定义函数,修改共享数据

index.js

点击查看代码
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

//集中管理多个组件共享的数据
export default new Vuex.Store({
  //集中定义共享数据
  state: {
    name: '未登录游客'
  },
  getters: {
  },
  //通过当前属性中定义的函数修改共享数据,必须是同步操作
  mutations: {
    setName(state,newName){
      state.name = newName
    }
  },
  //通过actions可以调用到mutations,在actions中可以进行异步操作
  actions: {
  },
  modules: {
  }
})

mutations中的函数不能直接调用,只能通过store对象的commit方法调用
调用mutations中的函数
App.vue

点击查看代码
<template>
  <div id="app">
    欢迎你,{{$store.state.name}}

    <input type="button" value="通过mutations修改共享数据" @click="handleUpdate"/>

    <img alt="Vue logo" src="./assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    HelloWorld
  },
  methods: {
    handleUpdate(){
      //mutations中定义的函数不能直接调用,必须通过这种方式来调用
      //setName为mutations中定义的函数名称,lisi为传递的参数
      this.$store.commit('setName','lisi')
    }
  }
}
</script>

在actions中定义函数,用于调用mutation
actions中定义的函数不能直接调用,只能通过store对象的dispatch方法调用

index.js

点击查看代码
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

//集中管理多个组件共享的数据
export default new Vuex.Store({
  //集中定义共享数据
  state: {
    name: '未登录游客'
  },
  getters: {
  },
  //通过当前属性中定义的函数修改共享数据,必须是同步操作
  mutations: {
    setName(state,newName){
      state.name = newName
    }
  },
  //通过actions可以调用到mutations,在actions中可以进行异步操作
  actions: {
    setNameByAxios(context){
      axios({
        url: '/api/admin/employee/login',
        method: 'post',
        data: {
          username: 'admin',
          password: '123456',
        }
      }).then(res => {
        if(res.data.code == 1){
          //异步请求后,需要修改共享数据
          context.commit('setName',res.data.data.name)
        }
      })
    }
  },
  modules: {
  }
})

App.vue

点击查看代码
<template>
  <div id="app">
    欢迎你,{{$store.state.name}}

    <input type="button" value="通过mutations修改共享数据" @click="handleUpdate"/>
    <input type="button" value="调用actions中定义的函数" @click="handleCallAction"/>

    <img alt="Vue logo" src="./assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    HelloWorld
  },
  methods: {
    handleUpdate(){
      //mutations中定义的函数不能直接调用,必须通过这种方式来调用
      //setName为mutations中定义的函数名称,lisi为传递的参数
      this.$store.commit('setName','lisi')
    },
    handleCallAction(){
      //调用actions中定义的函数,setNameByAxios为函数名称
      this.$store.dispatch('setNameByAxios')
    }
  }
}
</script>

vue.config.js

点击查看代码
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  }
})

(四)TypeScript

1.介绍:
TypeScript(简称:TS)是微软推出的开源语言
TypeScript是JavaScript的超集(JS有的TS都有)
TypeScript = Type + JavaScript(在JS基础上增加了类型支持)
TypeScript文件拓展名为ts
TypeScript可编译成标准的JavaScript,并且在编译时进行类型检查

全局安装typescript:npm install -g typescript
查看TS版本:tsc -v
通过tsc xxx.ts命令编译为js文件,node xxx.js执行
编译后的JS文件中类型会擦除

TS属于静态类型编程语言,JS属于动态类型编程语言
静态类型在编译期做类型检查,动态类型在执行期做类型检查
对于JS来说,需要等到代码执行的时候才能发现错误,对于TS来说,在代码编译的时候就可以发现错误
配合VSCode开发工具,TS可以提前到在编写代码的同时就发现代码中的错误,减少找Bug、改Bug的时间

2.常用数据类型

类型标注的位置:
标注变量
标注参数
标注返回值

点击查看代码
//字符串类型
let username: string = 'itcast'

//数字类型
let age: number = 20

//布尔类型
let isTrue: boolean = true

console.log(username)
console.log(age)
console.log(isTrue)

//字面量类型
function printText(s: string, alignment: 'left'|'right'|'center'){
    console.log(s, alignment)
}

printText('hello','left')
//printText(123,"left")
printText('hello','right')
//printText(hello,"abc")

//定义接口
interface Dog{
    name: string,
    age: number,
    color?: string //在属性名后面加?,表示当前属性为可选
}

//定义变量,并且指定为Dog类型
const d1: Dog = {name: '狗蛋', age: 1, color: 'black'}
const d2: Dog = {name: '狗蛋', age: 1}
//const d3: Dog = {name: '狗蛋'}
//const d4: Dog = {name: '狗蛋', age: 1, sex: '雄'}

//定义一个类,名称为User
//类中可以包含属性、构造方法、普通方法
class User {
    name: string; //指定类中的属性
    //构造方法
    constructor(name: string){ 
        this.name = name
    }

    //方法
    study(){
        console.log(this.name + '正在学习')
    }
}

//使用User类型
const user = new User('张三')

//输出类中的属性
console.log(user.name)

//调用类中的方法
user.study()

//class类——实现接口
//定义接口
interface Animal {
    name: string
    eat(): void
}

//定义一个类,实现上面的接口
class Cat implements Animal {
    name: string
    constructor(name: string){
        this.name = name
    }

    eat(): void {
        console.log(this.name + '吃鱼')
    }
}

//创建类型为Cat的对象
const c1 = new Cat('加菲猫')
console.log(c1.name)
c1.eat()

//class类——类的继承
class Ragdoll extends Cat{
    say() {
        console.log(this.name + '喵喵')
    }
}

const myRagdoll = new Ragdoll('小白')

myRagdoll.eat()
myRagdoll.say()
console.log(myRagdoll.name)

标签:axios,name,vue,Day01,笔记,js,Vue,import,data
From: https://www.cnblogs.com/overlord-lxy/p/18099347

相关文章

  • vue之实现单击与双击、同一标签使用click实现单双击操作、不选最后一个子元素的选择器
    MENUhtmlJavaScriptstyle解析html<template><divclass="box"><divclass="box_content"><pclass="box_p1"@click.prevent="tabSwitch({id:'keyId'})">......
  • 论文:Improving Entity Disambiguation by Reasoning over a Knowledge Base翻译笔记(通
    文章目录论文题目:通过在知识库中进行推理来改进实体消歧摘要1介绍2相关工作2.1带有知识库上下文的勃起功能障碍(ED)问题2.2基于知识图谱嵌入的ED2.3全局ED(实体解析)2.4多模块的实体识别3拟议的方法3.1任务表述3.2概述3.3提及表示3.4初始实体得分ψ~a~3.4.1实体......
  • vue extends继承后修改template的解决方案
    vueextends继承后怎么注入虚拟DOM节点1.需求使用extends继承一个组件并在上面做功能的修改和扩展,同时需要小小修改一部分的template。2.extend原理使用extends时,你实际上是创建了一个新组件,它包含了父组件的所有选项和数据,但是你可以覆盖或添加新的选项。3.问题修改通过ext......
  • jenkins使用笔记
    安装命令行dockerjenkins安装插件方法http://10.20.1.68:8080/pluginManager/advanced将升级站点地址改为http://updates.jenkins.io/update-center.jsonjenkins编译golanghttps://baijiahao.baidu.com/s?id=1709940320913165642&wfr=spider&for=pc选择一个自由风格......
  • web学习笔记(四十七)
    目录1.node.js中的三个全局变量1.1global1.2 __dirname 文件夹的绝对路径1.3 __filename 文件名的绝对路径2.模块化2.1什么是模块化2.2模块化的好处3.Node.js中模块化3.1 Node.js中的模块化规范4. Node.js中的模块作用域4.1module对象4.2  modul......
  • 王道操作系统个人向笔记-第一章
    目录操作系统的基本概念操作系统的概念操作系统的功能和目标操作系统的特征操作系统的发展历程手工操作阶段批处理阶段单道批处理系统多道批处理系统分时操作系统实时操作系统操作系统运行环境处理器运行模式中断和异常系统调用操作系统的体系结构操作系统的引导虚拟机操作系统的......
  • MIPI-CSI2笔记(2)
    参考资料:极客笔记 CSI-2Layer: 多条Lane和数据的分发:基于字节的传输,假设一共有四条lane:接收就是反序过程,经过这样的转换之后,一个packet在lane上的传输情况如下图所示: LowLevelProtocol协议层:短包和长包都是以字节单位存储的 长包和短包数据格式:包头PH:Data......
  • 【STM32】Gpio通用输入输出功能应用笔记
    文章目录一、前言1.1开发环境1.2GPIO电路原理1.3板卡电路原理1.3.1按键电路原理1.3.2Led电路原理1.3.3Beep电路原理二、功能实现2.1配置STM32Cubemx工程2.2KeilMDK工程编码2.2.1按键功能代码2.2.2LED灯功能代码2.2.3Beep功能代码2.2.4Main函数代码2.2.5K......
  • Vue 自定义组件库通过配置调整样式?
      在Vue自定义组件库中,通常可以通过配置来调整样式。为了实现这一点,你可以定义一组样式相关的配置项,并在组件内部使用这些配置项来动态地设置样式。以下是一个简单的示例,演示了如何通过配置调整组件的样式。自定义组件(CustomComponent.vue)<template><div:style......
  • 11-Vue-生命周期
    <!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>引出生命周期</title><scripttype="text/javascript"src="../js/vue.js"></script></head&......