How to implement a note-taking application using Vuex
This article mainly introduces the method of using Vuex to implement a note-taking application. Now I will share it with you and give you a reference.
I recently started to learn Vue. I first briefly went through the official documents, and then typed some DEMOs in the official documents, but I still don’t understand much. I found an entry-level note-taking application on the Internet. Even if it is an entry-level application, it is still difficult to learn. I will make this note for my study so that I can review it in the future. I also hope it can help female students who have just started learning Vue
expected goals
The notes are as follows Basic functions
1. Add
2. Delete
3. Collection
4. Switch between all notes and favorite notes
5. Search in the current list
Seller Show
Buyer Show
Preparation
1. Create a new project
Choose a folder to store the project. Here I use the Git Bush execution statement (the $ symbol comes with Git Bush), you can also Use the command line, the same
Select the project storage location
2. View the module (whether you like it or not)
View globally installed modules npm list --depth=0 -global
View globally installed modules
3. Create a project
Enter vue init webpack vuex-note on the command line and make settings to create a project
What the hell is this
4. Briefly explain what each configuration does
vue init webpack vuex-note: Initialize (init) a vue project built using the webpack build tool. The project name is vuex-note
Project name: Project name
Project description: Project description
Author: I
Vue build: Build method, divided into independent build and Runtime build, see the following link for specific instructions, here choose to build standalone independently https://vuejs.org/v2/guide/installation.html#Runtime-Compiler-vs-Runtime-only
Install vue-router: Do you need to install vue-router? It is used to jump to the page. It is not needed here. I will learn it later.
Use ESLint to lint your code: ESLint specification and It is used by law. Maybe the writing methods you are familiar with are not standard. If you use ESLint, you may get an error. Here, choose n
. The rest are for testing, n## all the way.
- #Should we run 'npm install' for you after the project has been created: If you need to directly install (npm install) related dependencies for you, just press Enter and we will install them for you. Kind of stuff
#5. There will be a prompt after installation, we will follow the prompts
First cd vuex-note to enter the vue just created Project folder6. Visit the page
At this time, you can open a new page by accessing localhost:8080 through the browser vue page7. Project structure
Deadline The current project structure is as shown in the figure8. Check out Vuex
Since Vuex is used to implement the note application , we should first check whether the built project contains the Vuex module.package.json file describes the files contained in the project, how the project runs and other information
package.json
9. Install Vuex
Enter npm install vuex --save on the command line: --save is to write the installation information into package.json
Vuex has been installed
At this point, all preliminary work has been completed, and the missing parts will be explained one by one during the implementation process
Start
Zero, idea
The entire application can be split into three components
开户
Each note includes four types of information: number (ID), title (title), content (content), and whether it has been collected (fav)
The state in Vuex must have a place to store all notes
The collection and deletion operations can only operate on the current notes, so I We also need a logo to record the current note (activeNote), which
contains two switching methods: all and favorites, so we also need a logo to distinguish it, let's call it show. , all represents all, fav represents the collection
Component ==> actions.js ==> mutations.js = > state: Call the method in actions through the component ( dispatch), call the method in mutations (commit) through the method in actions, and use the method in mutations to operate the note list in the state (notes), the current note (activeNote), etc.
1. index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <title>vuex-note</title> </head> <body> <p id="app"></p> <!-- built files will be auto injected --> </body> </html>
There is nothing to say about this, just pay attention to the ID of p
2. main.js
import Vue from 'vue' import App from './App' import store from './store' Vue.config.productionTip = false new Vue({ el: '#app', store, components: { App }, template: '<App/>' })
1. When is importing need' ./ '?
Export from the project module, you do not need ./ when importing, but you need ./ when importing from a component written by yourself
2. When is import { aaa} from abc The introduction of this kind of braces? When is it not needed?
When the exported part in abc is export aaa
When the import is the part exported by export default, {} is not added, and an alias can be used
3. There is no store file in the project structure, only the store folder. What does import store from './store' mean?
I don’t know, please give me some advice
4. What does a separate store in new Vue mean?
An abbreviation of ES6, the abbreviation is preceded by store:store. This sentence means to inject Vuex globally, so that the state library can be called through this.$store in each component. , if it is not injected globally, it needs to be introduced separately in each component. It will be very troublesome if there are too many.
3. Index.js under store
import Vue from 'vue' import Vuex from 'vuex' import getters from './getters' import mutations from './mutations' import actions from './actions' Vue.use(Vuex) const defaultNote = { id: +new Date(), title: '新建笔记' + new Date().getMilliseconds(), // 加时间是为了做一下区分 content: '笔记内容', fav: false } // 可以理解为一个状态的仓库 const state = { notes: [defaultNote], // 以数组方式存放所有的笔记 activeNote: defaultNote, // 用来记录当前笔记 show: 'all' // 用于切换 全部 / 已收藏 两种不同列表的标识 } export default new Vuex.Store({ state, getters, mutations, actions })
1. What does Vue.use(Vuex) mean?
Using Vuex, you will have to do this when using Vue-router in the future, but it must be written in the index.js file under the route folder
2. What does new Date() mean?
Another way to get timestamp, which is equivalent to new Date().getTime()
3. The relationship between state, getters, mutations, actions ?
state: State warehouse as mentioned above
getters: modification of state, for example, there is an attribute like str: "abc" in state, which is required in many components To perform str "def" operation, it would be too troublesome to perform str "def" operation on each component, so you can add in getters:
strAdd(){ return this.str + "abc" }
Just use strAdd in the component in the future
mutations: Simply put, it is used to modify state, synchronous method. Regularly call this.$store.commit
actions: Simply speaking, it is used to call mutations, asynchronous method. Regular call this.$store.dispatch
4. tool.vue
<template> <p id="tool"> <button class="add" @click="add_note">新增</button> <button class="fav" @click="fav_note">收藏</button> <button class="del" @click="del_note">删除</button> </p> </template> <script type="text/javascript"> import { mapState, mapGetter, mapActions } from 'vuex' export default { name: 'tool', methods:{ ...mapActions(['add_note','del_note','fav_note']) } } </script> <style type="text/css" scoped> #tool { width: 200px; height: 600px; border: 2px solid #ccc; float: left; } button { width: 100%; height: calc(100% / 3); font-size: 60px; } </style>
1. What are mapState, mapGetter, and mapActions?
Here is a very good explanation http://www.imooc.com/article/14741
In addition, when methods and Vuex actions have attribute A with the same name , you can use mapActions(['A']) This method is abbreviated as
Note: 1. The square brackets cannot be omitted; 2. The square brackets are strings; 3. The expansion operator... You cannot omit
and you can also use an alias. It is written as follows. Note that [] becomes {}:
...map({ 本组件的属性 : Vuex 中 actions 中的属性 })
需要传入参数时,前提是 actions 中的属性(方法)能接收参数:
methods:{ ...mapActions(['abc']) // 自定义一个方法,通过触发这个方法调用之前重名的方法并传入参数 tragger_abc(参数){ this.abc(参数) } }
2.scoped
对当前组件生效的 CSS
3.calc
使用时记得在运算符前后各加一个空格
五、list.vue
<template> <p id="list"> <p class="switch"> <button class="all" @click='get_switch_note("all")'>全部</button><button class="fav" @click='get_switch_note("fav")'>已收藏</button> </p> <p class="search"> <input type="text" placeholder="在这里搜索" v-model="search" /> </p> <p class="noteList"> <p class="note" v-for="note in search_filteredNote" :class="{favColor:note.fav===true,active:note.id===activeNote.id}" @click='get_select_note(note)'> <p class="title"> <p>{{note.title}}</p> </p> <p class="content"> <p>{{note.content}}</p> </p> </p> </p> </p> </template> <script type="text/javascript"> import { mapState, mapGetters, mapActions } from 'vuex' export default { name: 'list', data: function() { return { search: "" } }, computed: { ...mapState(['notes', 'activeNote']), ...mapGetters(['filteredNote']), // 二次过滤:在当前列表(全部 或 已收藏)中进行筛选,返回值被用在组件的 v-for 中 search_filteredNote() { if(this.search.length > 0) { // 如果输入框有值,返回二次过滤的结果并加载 return this.filteredNote.filter(note => { if(note.title.indexOf(this.search) > 0) { return note } }) } else { // 输入框没值,不过滤,直接拿来加载 return this.filteredNote } } }, methods: { ...mapActions(['select_note', 'switch_note']), get_select_note(note) { this.select_note(note) }, get_switch_note(type) { this.switch_note(type) } } } </script> <style type="text/css" scoped="scoped"> #list { width: 300px; height: 600px; border: 2px solid #ccc; float: left; margin-left: 10px; display: flex; flex-direction: column; } p { margin: 0; } .switch {} .switch button { height: 60px; width: 50%; font-size: 40px; } .search { border: 1px solid #CCCCCC } input { width: 100%; box-sizing: border-box; height: 50px; line-height: 50px; padding: 10px; outline: none; font-size: 20px; border: none; } .noteList { flex-grow: 1; overflow: auto; } .note { border: 1px solid #CCCCCC; } .favColor { background: pink; } .active { background: lightblue } </style>
1.data 中的 search 是干嘛的?可不可以写在 computed 中?
用来与搜索框进行关联。可以写在 computed 中,但 computed 中的属性默认都是 getter ,就是只能获取值,如果想修改,需要设置 setter ,详见官方文档
六、edit.vue
<template> <p id="edit"> <p class="title"> <input type="text" placeholder="在这里输入标题" v-model="activeNote.title"/> </p> <p class="content"> <textarea name="" placeholder="在这里吐槽" v-model="activeNote.content"></textarea> </p> </p> </template> <script type="text/javascript"> import { mapState, mapGetter, mapActions } from 'vuex' export default { name: 'edit', computed:{ ...mapState(['activeNote']) // 当本组件中 computed 中的属性名与 Vuex 中的 state 属性名相同时,就可以在 mapState() 中简写 } } </script> <style type="text/css" scoped="scoped"> #edit { width: 300px; height: 600px; border: 2px solid #ccc; float: left; margin-left: 10px; display: flex; flex-direction: column; } .title { border: 1px solid #CCCCCC; } input { width: 100%; box-sizing: border-box; height: 50px; line-height: 50px; padding: 10px; outline: none; font-size: 20px; border: none; } .content { flex-grow: 1; background: orange; display: flex; flex-direction: column; } textarea { width: 100%; box-sizing: border-box; flex-grow: 1; resize: none; padding: 10px; font-size: 20px; outline: none; font-family: inherit; } </style>
七、actions.js
export default { add_note({commit}) { commit('ADD_NOTE') }, select_note({commit}, note) { commit("SELECT_NOTE", note) }, del_note({commit}) { commit("DEL_NOTE") }, fav_note({commit}) { commit("FAV_NOTE") }, switch_note({commit}, type) { commit("SWITCH_NOTE", type) } }
1.这是干什么?
这里的每个方法实际上是通过 commit 调用 mutations.js 中的方法;
举个栗子:tool.vue 的 新增 按钮上绑了一个 add_note 自定义方法,在 actions.js 中也定义一个同名的方法,这样就可以在 tool.vue 中的 mapActions 中简写,就是下面这句:
# tool.vue ...mapActions(['add_note','del_note','fav_note'])
而 actions.js 中的 add_note 去调用 mutations.js 中写好的 ADD_NOTE 方法,而实际的添加操作也是在 ADD_NOTE 中,组件也好,actions 也好,最终只是调用 ADD_NOTE 。之所以这么做是因为 mutations 中的方法都是同步的,而 actions 中的方法是异步的,不过在本例里没啥区别
八、getters.js
export default { filteredNote: (state) => { if(state.show === 'all') { return state.notes } else { return state.notes.filter((note) => { if(note.fav === true) { return note } }) } } }
实现一个过滤,根据 show 来判断展示 全部笔记 还是 已收藏笔记
九、mutations.js
import { SWITCH_NOTE, ADD_NOTE, SELECT_NOTE, DEL_NOTE, FAV_NOTE } from './mutation-types' export default { [ADD_NOTE](state, note = { id: +new Date(), title: '新建笔记' + new Date().getMilliseconds(), content: '笔记内容', fav: false }) { state.notes.push(note) state.activeNote = note }, [SELECT_NOTE](state, note) { state.activeNote = note }, [DEL_NOTE](state) { for(let i = 0; i < state.notes.length; i++) { if(state.notes[i].id === state.activeNote.id) { state.notes.splice(i, 1) state.activeNote = state.notes[i] || state.notes[i - 1] || {} return } } }, [FAV_NOTE](state) { state.activeNote.fav = !state.activeNote.fav }, [SWITCH_NOTE](state, type) { state.show = type } }
1.export default 那里看着好熟悉
ES6 函数的一种写法,中括号 + 常量 作为函数名,这里常量从其它文件引入
十、mutation-types.js
export const ADD_NOTE = "ADD_NOTE" export const SELECT_NOTE = "SELECT_NOTE" export const DEL_NOTE = "DEL_NOTE" export const FAV_NOTE = "FAV_NOTE" export const SWITCH_NOTE = "SWITCH_NOTE"
抛出常量,mutations.js 中的函数常量就是这里抛出的,查资料说是这么做便于一目了然都有那些方法。
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
The above is the detailed content of How to implement a note-taking application using Vuex. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to delete Xiaohongshu notes? Notes can be edited in the Xiaohongshu APP. Most users don’t know how to delete Xiaohongshu notes. Next, the editor brings users pictures and texts on how to delete Xiaohongshu notes. Tutorial, interested users come and take a look! Xiaohongshu usage tutorial How to delete Xiaohongshu notes 1. First open the Xiaohongshu APP and enter the main page, select [Me] in the lower right corner to enter the special area; 2. Then in the My area, click on the note page shown in the picture below , select the note you want to delete; 3. Enter the note page, click [three dots] in the upper right corner; 4. Finally, the function bar will expand at the bottom, click [Delete] to complete.

Notes deleted from Xiaohongshu cannot be recovered. As a knowledge sharing and shopping platform, Xiaohongshu provides users with the function of recording notes and collecting useful information. According to Xiaohongshu’s official statement, deleted notes cannot be recovered. The Xiaohongshu platform does not provide a dedicated note recovery function. This means that once a note is deleted in Xiaohongshu, whether it is accidentally deleted or for other reasons, it is generally impossible to retrieve the deleted content from the platform. If you encounter special circumstances, you can try to contact Xiaohongshu’s customer service team to see if they can help solve the problem.

As a Xiaohongshu user, we have all encountered the situation where published notes suddenly disappeared, which is undoubtedly confusing and worrying. In this case, what should we do? This article will focus on the topic of "What to do if the notes published by Xiaohongshu are missing" and give you a detailed answer. 1. What should I do if the notes published by Xiaohongshu are missing? First, don't panic. If you find that your notes are missing, staying calm is key and don't panic. This may be caused by platform system failure or operational errors. Checking release records is easy. Just open the Xiaohongshu App and click "Me" → "Publish" → "All Publications" to view your own publishing records. Here you can easily find previously published notes. 3.Repost. If found

Link AppleNotes on iPhone using the Add Link feature. Notes: You can only create links between Apple Notes on iPhone if you have iOS17 installed. Open the Notes app on your iPhone. Now, open the note where you want to add the link. You can also choose to create a new note. Click anywhere on the screen. This will show you a menu. Click the arrow on the right to see the "Add link" option. click it. Now you can type the name of the note or the web page URL. Then, click Done in the upper right corner and the added link will appear in the note. If you want to add a link to a word, just double-click the word to select it, select "Add Link" and press

How to add product links in notes in Xiaohongshu? In the Xiaohongshu app, users can not only browse various contents but also shop, so there is a lot of content about shopping recommendations and good product sharing in this app. If If you are an expert on this app, you can also share some shopping experiences, find merchants for cooperation, add links in notes, etc. Many people are willing to use this app for shopping, because it is not only convenient, but also has many Experts will make some recommendations. You can browse interesting content and see if there are any clothing products that suit you. Let’s take a look at how to add product links to notes! How to add product links to Xiaohongshu Notes Open the app on the desktop of your mobile phone. Click on the app homepage

Vue2.x is one of the most popular front-end frameworks currently, which provides Vuex as a solution for managing global state. Using Vuex can make state management clearer and easier to maintain. The best practices of Vuex will be introduced below to help developers better use Vuex and improve code quality. 1. Use modular organization state. Vuex uses a single state tree to manage all the states of the application, extracting the state from the components, making state management clearer and easier to understand. In applications with a lot of state, modules must be used

What does Vuex do? Vue official: State management tool What is state management? State that needs to be shared among multiple components, and it is responsive, one change, all changes. For example, some globally used status information: user login status, user name, geographical location information, items in the shopping cart, etc. At this time, we need such a tool for global status management, and Vuex is such a tool. Single-page state management View–>Actions—>State view layer (view) triggers an action (action) to change the state (state) and responds back to the view layer (view) vuex (Vue3.

As a lifestyle sharing platform, Xiaohongshu covers notes in various fields such as food, travel, and beauty. Many users want to share their notes on Xiaohongshu but don’t know how to do it. In this article, we will detail the process of posting notes on Xiaohongshu and explore how to block specific users on the platform. 1. How to publish notes tutorial on Xiaohongshu? 1. Register and log in: First, you need to download the Xiaohongshu APP on your mobile phone and complete the registration and login. It is very important to complete your personal information in the personal center. By uploading your avatar, filling in your nickname and personal introduction, you can make it easier for other users to understand your information, and also help them pay better attention to your notes. 3. Select the publishing channel: At the bottom of the homepage, click the "Send Notes" button and select the channel you want to publish.
