<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>插槽指令</title> <style> body { font-size: 30px; } li:hover { color: orange; cursor: pointer; } .del:hover { color: red; } </style> </head> <body> <div id="app"> <p> <input type="text" v-model="info"> <button @click="add_msg">留言</button> <ul> <msg-tag :msg="msg" v-for="(msg, i) in msgs" :key="msg"> <!--template經過v-slot綁定子組件內部slot插槽標籤的name屬性值--> <template v-slot:del_btn> <span @click="del_fn(i)" class="del">x</span> </template> </msg-tag> </ul> </p> </div> </body> <script src="js/vue.js"></script> <script> let msgTag = { props: ['msg'], template: ` <li> <!--slot標籤是在子組件中佔位,父組件模板中能夠經過name名字來填充--> <slot name="del_btn"></slot> <span>{{ msg }}</span> </li> `, }; new Vue({ el: '#app', components: { msgTag }, data: { info: '', msgs: JSON.parse(sessionStorage.msgs || '[]'), }, methods: { add_msg() { let info = this.info; if (info) { this.msgs.unshift(this.info); this.info = ''; sessionStorage.msgs = JSON.stringify(this.msgs); } }, del_fn(index) { console.log(index); this.msgs.splice(index, 1); sessionStorage.msgs = JSON.stringify(this.msgs); } } }); </script> </html>
環境css
1)安裝node:官網下載安裝包,傻瓜式安裝:https://nodejs.org/zh-cn/ 2)安裝cnpm >:npm install -g cnpm --registry=https://registry.npm.taobao.org 3)安裝腳手架 >:cnpm install -g @vue/cli 4)清空緩存處理(若是第二、3補出問題能夠執行該條命令) >:npm cache clean --force
建立項目html
項目目錄介紹vue
|vue-proj | |node_modules 項目依賴 | |public | | | 圖標、單頁面.html | |src | | |assets 靜態文件(img、css、js) | | |components 小組件 | | |views 頁面組件 | | |App.vue 根組件 | | |main.js 主腳本文件 | | |router.js 安裝vue-router插件的腳本文件 - 配置路由的 | | |store.js 安裝vuex插件的腳本文件 - 全局倉庫 - 數據共享 | |配置文件們 | |README.md 關鍵命令說明
main.jsnode
// import 別名 from '文件(後綴能夠省略)' import Vue from 'vue' // import App from './App.vue' import App from './App' // 導入時能夠省略後綴 import router from './router' // .表明相對路徑的當前路徑 import store from '@/store.js' // @表示src絕對路徑 Vue.config.productionTip = false; // new Vue({ // router, // store, // render: h => h(App) // }).$mount('#app'); new Vue({ el: '#app', router: router, store, // render: (fn) => { // return fn(App) // } render (fn) { // 讀取組件渲染給掛載點el return fn(App) } });
組件 .vue 文件:模板(template) + 腳本(scpirt) + 樣式(style)vue-router
<template> <!--組件有且只有一個根標籤--> <div id="app"> <h1 @click="btnClick">{{ title }}</h1> </div> </template> <script> // 組件內部導出,其它文件才能import導入該組件 export default { name: "App", data() { return { title: '主頁' } }, methods: { btnClick() { console.log(this.title) } } } </script> <!--scoped樣式組件局部化--> <style scoped> h1 { color: red; } </style>