官术网_书友最值得收藏!

Saving the notes with the deep option

Now, we would like to save and restore the notes between sessions, just like we did for the note content:

  1. Let's create a new saveNotes method. Since we can't save an array of objects directly into the localStorage API (it only accepts strings), we need to convert it to JSON first with JSON.stringify:
      methods: {
        ...
  
        saveNotes () {
          // Don't forget to stringify to JSON before storing
          localStorage.setItem('notes', JSON.stringify(this.notes))
          console.log('Notes saved!', new Date())
        },
      },

Like we did for the previous content property, we will watch the notes data property for changes to trigger the saveNotes method.

  1. Add a watcher in the watch option:
      watch: {
        notes: 'saveNotes',
      }

Now, if you try to add a few tasks, you should see something like this in your console:

Notes saved! Mon Apr 42 2042 17:40:23 GMT+0100 (Paris, Madrid)
Notes saved! Mon Apr 42 2016 17:42:51 GMT+0100 (Paris, Madrid)
  1. Change the initialization of the notes property in the data hook to load the stored list from localStorage:
      data () {
        return {
          notes: JSON.parse(localStorage.getItem('notes')) || [],
          selectedId: null,
        }
      },

The newly added notes should be restored when you refresh the page. However, if you try to change the content of one note, you will notice that it doesn't trigger the notes watcher, and thus, the notes are not saved. This is because, by default, the watchers are only watching the direct changes to the target object--assignment of a simple value, adding, removing, or moving an item in an array. For example, the following operations will be detected by default:

// Assignment
this.selectedId = 'abcd'

// Adding or removing an item in an array
this.notes.push({...})
this.notes.splice(index, 1)

// Sorting an array
this.notes.sort(...)

However, all the other operations, like these, will not trigger the watcher:

// Assignment to an attribute or a nested object
this.myObject.someAttribute = 'abcd'
this.myObject.nestedObject.otherAttribute = 42

// Changes made to items in an array
this.notes[0].content = 'new content'

In this case, you will need to add the deep option to the watcher:

watch: {
  notes: {
    // The method name
    handler: 'saveNotes',
    // We need this to watch each note's properties inside the array
    deep: true,
  },
}

That way, Vue will also watch the objects and attributes recursively inside our notes array. Now, if you type into the text editor, the notes list should be saved--the v-model directive will modify the content property of the selected note, and with the deep option, the watcher will be triggered.

主站蜘蛛池模板: 岳池县| 阿拉尔市| 尼勒克县| 诏安县| 砀山县| 金山区| 双城市| 大兴区| 资兴市| 柏乡县| 阿克苏市| 株洲县| 满城县| 许昌市| 巩留县| 闻喜县| 杨浦区| 子洲县| 方城县| 万全县| 城口县| 朝阳市| 南江县| 伽师县| 宁晋县| 吉木乃县| 深州市| 乌鲁木齐县| 望江县| 舞阳县| 泰宁县| 荃湾区| 晋城| 宁城县| 柘荣县| 永嘉县| 陇西县| 任丘市| 东乌| 庆阳市| 红安县|