代码库
迷你vue
高频知识点
<script>
/*
https://cn.vuejs.org/tutorial/
*/
// 给每个 todo 对象一个唯一的 id
let id = 0
export default {
data() {
return {
message: 'Hello World!',
titleClass: 'title',
count: 0,
text: "",
awesome: true,
hideCompleted: false,
newTodo: '',
todos: [
{id: id++, text: 'Learn HTML', done: true},
{id: id++, text: 'Learn JavaScript', done: true},
{id: id++, text: 'Learn Vue', done: false}
],
todoId: 1,
todoData: null
}
},
methods: {
increment() {
this.count++
},
toggle() {
this.awesome = !this.awesome
},
addTodo() {
this.todos.push({id: id++, text: this.newTodo, done: false})
this.newTodo = ''
},
removeTodo(todo) {
this.todos = this.todos.filter((t) => t !== todo)
},
async fetchData() {
this.todoData = null
const res = await fetch(
`https://jsonplaceholder.typicode.com/todos/${this.todoId}`
)
this.todoData = await res.json()
}
},
// 计算属性
computed: {
filteredTodos() {
return this.hideCompleted
? this.todos.filter((t) => !t.done)
: this.todos
}
},
// 生命周期钩子
mounted() {
// 此时组件已经挂载
this.$refs.pElementRef.textContent = 'mounted!'
this.fetchData()
},
// 监听器
watch: {
todoId() {
this.fetchData()
}
}
}
</script>
<template>
<!-- Attribute绑定 -->
<!-- v-bind的简写 -->
<h1 :class="titleClass">{{ message }}</h1>
<!-- 事件监听 -->
<!-- v-on的简写 -->
<button @click="increment">Count is: {{ count }}</button>
<!-- 表单绑定-->
<input v-model="text">
<p>{{ text }}</p>
<!-- 条件渲染 -->
<button @click="toggle">Toggle</button>
<h1 v-if="awesome">Vue is awesome!</h1>
<h1 v-else>Oh no😢</h1>
<form @submit.prevent="addTodo">
<input v-model="newTodo" required placeholder="new todo">
<button>Add Todo</button>
</form>
<!--列表渲染-->
<ul>
<li v-for="todo in filteredTodos" :key="todo.id">
<input type="checkbox" v-model="todo.done">
<span :class="{ done: todo.done }">{{ todo.text }}</span>
<button @click="removeTodo(todo)">X</button>
</li>
</ul>
<button @click="hideCompleted = !hideCompleted">
{{ hideCompleted ? 'Show all' : 'Hide completed' }}
</button>
<!-- 生命周期和模板引用 -->
<p ref="pElementRef">Hello</p>
<!-- 监听器 -->
<p>Todo id: {{ todoId }}</p>
<button @click="todoId++" :disabled="!todoData">Fetch next todo</button>
<p v-if="!todoData">Loading...</p>
<pre v-else>{{ todoData }}</pre>
</template>
<style>
.title {
color: red;
}
.done {
text-decoration: line-through;
}
</style>
<script>
export default {
// 从父组件接受动态数据
props: {
msg: String
},
// 向父组件触发事件
emits: ['response'],
created() {
this.$emit('response', 'hello from child')
}
}
</script>
<template>
<h2>{{ msg || 'No props passed yet' }}</h2>
<!-- 插槽 -->
<slot>Fallback content</slot>
</template>
http客户端
https://github.com/imcvampire/vue-axios
import {createApp} from 'vue';
import axios from 'axios'
import VueAxios from 'vue-axios'
const app = createApp(App);
// https://github.com/imcvampire/vue-axios
app.use(VueAxios, axios)
// 多个axios实例
app.use(VueAxios,
{
// 第一个axios实例
$gitee: axios.create({
baseURL: "https://gitee.com/api/v5",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
}
}),
// 第二个axios实例
$github: axios.create({
baseURL: "https://api.github.com",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
}
})
})
// 挂载id=vue-app的html节点
app.mount('#vue-app');
<script>
// 选项式API
export default {
name: 'App',
methods: {
getList() {
this.axios.get(api).then((response) => {
console.log(response.data)
})
// or
this.$http.get(api).then((response) => {
console.log(response.data)
})
}
}
}
</script>
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
type Response struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data map[string]string `json:"data"`
}
// SourceAuth 封装一个函数, 演示如何post一个接口, 并处理返回的数据
func SourceAuth(SrcName string) (http.Header, error) {
// 创建一个POST请求
url := "https://xxxx.com/auth"
postData := map[string]string{"srcname": SrcName}
// 创建一个HTTP客户端
client := &http.Client{}
// 将map转换为json字符串
jsonData, err := json.Marshal(postData)
if err != nil {
return nil, err
}
// 创建一个POST请求
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
return nil, err
}
// 设置请求头
req.Header.Set("Content-Type", "application/json")
// 发送请求并获取响应
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending request:", err)
return nil, err
}
defer resp.Body.Close()
// 读取响应内容
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
return nil, err
}
var res Response
err = json.Unmarshal(body, &res)
if err != nil {
return nil, err
}
if res.Code != 0 {
return nil, fmt.Errorf("request failed, code=%d, msg=%s", res.Code, res.Msg)
}
var headers = resp.Header
for key, value := range res.Data {
headers.Add(key, value)
}
return headers, nil
}
func main() {
headers, err := SourceAuth("xxxx")
if err != nil {
fmt.Println("Error reading response body:", err)
}
fmt.Println(headers)
}
import requests
response = requests.get('http://python.org')
print(response.text)
import aiohttp
async with aiohttp.ClientSession() as session:
async with session.get('http://python.org') as response:
print(await response.text())
集成ui框架
https://bootstrap-vue-next.github.io/bootstrap-vue-next/docs.html#installation-vue-js
import { createApp } from 'vue';
import {createBootstrap} from 'bootstrap-vue-next'
import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap-vue-next/dist/bootstrap-vue-next.css'
const app = createApp(App);
// https://bootstrap-vue-next.github.io/bootstrap-vue-next/docs.html#installation-vue-js
app.use(createBootstrap())
// 挂载id=vue-app的html节点
app.mount('#vue-app');
// vite.config.js/ts
import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'
import Components from 'unplugin-vue-components/vite'
import {BootstrapVueNextResolver} from 'bootstrap-vue-next'
export default defineConfig({
plugins: [
vue(),
Components({
// 自动注册bootstrap-vue-next组件
resolvers: [BootstrapVueNextResolver()],
}),
],
})