我在写一个仿markdown的vue程序
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=" initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>notebook</title>
<!-- Icons & Stylesheets -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="style.css" />
</head>
<body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<!--add the marked library:-->
<script src="https://unpkg.com/marked"></script>
</body>
<!--Notebook app-->
<div id="notebook">
<!-- sidebar-->
<aside class="side-bar">
<!--Toolbar-->
<div class="toolbar">
<!-- Add note button -->
<button :title="addButtonTitle" @click="addNote"><i class="material-icons">add</i>Add note</button>
</div>
<div class="notes">
<!--Note list here-->
<div class="note" v-for="note in notes" @click="selectNote(note)">{{ note.title }}</div>
</div>
</aside>
<!--Main pane-->
<section class="main">
<textarea v-model="selectedNote.content"></textarea>
</section>
<aside class="preview" v-html="notePreview">
</aside>
</div>
<!--some javascript -->
<script src="script.js"></script>
</html>
new Vue({
// css selector of the root DOM element
el: '#notebook',
// some data
data () {
return {
content: localStorage.getItem('content') || 'you can write in **markdown**',
// New! a note array
notes: [],
selectedId: localStorage.getItem('selected-id') || null,
}
},
computed: {
notePreview () {
//markdown rendered to HTML
return this.selectedNote? marked(this.selectedNote.content):""
// return marked(this.content);
},
addButtonTitle () {
return this.notes.length + "notes already"
},
selectedNote () {
// we return the matching note with selectedId
return this.notes.find(note => note.id === this.selectedId)
// this.selectedId = note.id
},
},
watch: {
// watching 'content' data property
content:
{
handler:'saveNote',
deep: true,
selectedId(val, oldVal) {
localStorage.setItem('selected-id', val)
},
},
},
methods: {
// Add a note with some default content and select it
addNote () {
const time = Date.now()
// Default new note
const note = {
id: String(time),
title: 'New note' + (this.notes.length + 1),
content: '**Hi!** This new note is using [markdown](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) for formatting!',
created: time,
favorite: false,
}
// Add to this list
this.notes.push(note)
},
selectNote (note) {
this.selectedId = note.id
},
saveNote() {
localStorage.setItem('content',this.content)
},
}})
可是现在总是报错 TypeError: Cannot read property 'content' of undefined" 不知道哪里错了????
你代码中 写的是 <textarea v-model="selectedNote.content"></textarea> 即 content 这个变量的值,是定义在 seleectNote 这个对象中,那你要检查你这个对象中这个属性有没有值,或者有没有获取到值,如果没有值,或者没有动态获取到那你在使用它的时候就会报undefined