Javascript [Vue warn]:渲染时出错:“Vue warn”;TypeError:无法读取属性';文本';“未定义”的定义;

Javascript [Vue warn]:渲染时出错:“Vue warn”;TypeError:无法读取属性';文本';“未定义”的定义;,javascript,ruby-on-rails,vue.js,slim,Javascript,Ruby On Rails,Vue.js,Slim,我试图在axios post之后将对象推送到标记数组,但推对象时出现此错误 [Vue warn]:呈现错误:“TypeError:无法读取未定义的属性“text” 这是怎么回事 对不起,我的问题不好。我还只是个初学者 一开始它是有效的,但我做了一些事情,但它不起作用 我打电话给“文本”不是为了什么 javascript/packs/index_vue.js new Vue ({ el: '#tags', methods: { ~~~~~~~~~~omit~~~~~~~~~~~

我试图在axios post之后将对象推送到标记数组,但推对象时出现此错误

[Vue warn]:呈现错误:“TypeError:无法读取未定义的属性“text”

这是怎么回事

对不起,我的问题不好。我还只是个初学者

一开始它是有效的,但我做了一些事情,但它不起作用

我打电话给“文本”不是为了什么

javascript/packs/index_vue.js

new Vue ({
    el: '#tags',
    methods: {
~~~~~~~~~~omit~~~~~~~~~~~
      addTag: function(){
        this.submitting = true;
        const newTag = {
          tag: {
            title: this.newTagTitle,
            status: 0,
            tasks: []
          }
        }
        axios.post('/api/tags', newTag)
          .then((res) => {
            console.log('just created a tag')
            this.tags.push(newTag);  //error occurring here
            this.newTagTitle = '';
            this.submitting = false;
            this.showNewTagForm = false;
          }).catch(error => {
            console.log(error);
          });
      },
      addTask: function(tagId, i) { // added by edit
        const newTask = {
          task: {
            text: this.newTaskTextItems[i].text,
            deadline: this.newTaskDeadlineItems[i].deadline,
            priority: this.newTaskPriorityItems[i].selected
          },
          tag_task_connection: {
            tag_id: tagId
          }
        }
        axios.post('/api/task/create', newTask)
          .then(() => {
            console.log('just created a task')
            newTask.task.limit = Math.ceil((parseDate(this.newTaskDeadlineItems[i].deadline).getTime() - new Date().getTime())/(1000*60*60*24));
            this.tags[i].tasks.push(newTask.task);
            this.newTaskTextItems[i].text = '',
            this.newTaskDeadlineItems[i].deadline = '',
            this.newTaskPriorityItems[i].selected = '',
            newTask.tasks = '',
            newTask.tag_task_connection = ''
          }).catch(error => {
            console.log(error);
        });
      }
~~~~~~~~~~omit~~~~~~~~~~~
    },
    mounted: function () {
      axios.get('/api/tags')
      .then( res => {
        this.tags = res.data.tags,
        this.newTaskTextItems = res.data.newTaskTextItems,
        this.newTaskDeadlineItems = res.data.newTaskDeadlineItems,
        this.newTaskPriorityItems = res.data.newTaskPriorityItems,
        this.checkedItems = res.data.checkedItems
      })
    },
    data: {
      tags: [],
      options: [
        { name: "低", id: 1 },
        { name: "中", id: 2 },
        { name: "高", id: 3 }
      ],
      showNewTagForm: false,
      showStatusFrom: false,
      changeStatusTag: 0,
      deleteConf: false,
      deleteTarget: 0,
      helloWorld: false,
      firstModal: true,
      newTagTitle: '',
      loading: false,
      submitting: false,
      newTaskTextItems: '',
      newTaskDeadlineItems: '',
      newTaskPriorityItems: ''
    }
~~~~~~~~~~omit~~~~~~~~~~~
})
10:43:20 web.1     | Started POST "/api/tags" for ::1 at 2020-09-11 10:43:20 +0900
10:43:20 web.1     | Processing by Api::TagsController#create as JSON
10:43:20 web.1     |   Parameters: {"tag"=>{"title"=>"create_tag_test7", "status"=>0, "tasks"=>[]}}
10:43:20 web.1     | Unpermitted parameter: :tasks
10:43:20 web.1     |    (0.1ms)  begin transaction
10:43:20 web.1     |   ↳ app/controllers/api/tags_controller.rb:14:in `create'
10:43:20 web.1     |   Tag Create (0.9ms)  INSERT INTO "tags" ("title", "status", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["title", "create_tag_test7"], ["status", 0], ["created_at", "2020-09-11 01:43:20.356248"], ["updated_at", "2020-09-11 01:43:20.356248"]]
10:43:20 web.1     |   ↳ app/controllers/api/tags_controller.rb:14:in `create'
10:43:20 web.1     |    (7.3ms)  commit transaction
10:43:20 web.1     |   ↳ app/controllers/api/tags_controller.rb:14:in `create'
10:43:20 web.1     | No template found for Api::TagsController#create, rendering head :no_content
10:43:20 web.1     | Completed 204 No Content in 13ms (ActiveRecord: 8.2ms | Allocations: 2708)
views/tags/index.html.slim

.tags
  .tag v-for="(tag, i) in tags" :key="i"
    .tag-top
      .title
        h2 v-text="tag.title"
      .status.todo v-if="tag.status==0" v-on:click="openStatusForm(tag.id)" 未着手
      .status.going v-else-if="tag.status==1" v-on:click="openStatusForm(tag.id)" 進行中
      .status.done v-else-if="tag.status==2" v-on:click="openStatusForm(tag.id)" 完了
      .delete-button v-if="tag.status==0 || tag.status==1 || tag.status==2"
        button.delete.del-modal v-on:click="openDeleteConf(tag.id)" 削除
    .tag-content
      form.task-form
        .task-form-top
          input.text type="text" required="" name="text" placeholder="タスクを入力。" v-model="newTaskTextItems[i].text"
        .task-form-bottom
          .deadline-form
            p 締め切り
            input.deadline type="date" name="deadline" required="" v-model="newTaskDeadlineItems[i].deadline"
          .priority-form
            p 優先度
            v-select :options="options" v-model="newTaskPriorityItems[i].selected" label="name" :reduce="options => options.id" name="priority" placeholder="選択してください"
          .task-form-button
             button type="button" v-on:click="addTask(tag.id, i)" タスクを作成
      form.tasks
        .task v-for="(task, j) in tag.tasks" :key="j"
          .task-content :class="{ done: tag.tasks[j].checked }"
            .task-top
              .check
                input.checkbox_check type="checkbox" :value='task.id' v-model="tag.tasks[j].checked" :id="'task' + j"
              .task-title :class="{ checked: tag.tasks[j].checked }" v-text="task.text"
              .task-priority
                .task-priority-title 優先度:
                .task-priority-mark.low v-if="task.priority==1" 低
                .task-priority-mark.middle v-else-if="task.priority==2" 中
                .task-priority-mark.high v-else-if="task.priority==3" 高
      .task-bottom
              .deadline.tip v-if="task.limit<0" 締め切りを過ぎています
              .deadline.tip v-else-if="task.limit==0" 本日締め切り
              .deadline(v-else) あと{{ task.limit }}日
        .task-clear
          button type="button" v-on:click="clearTasks(tag.id)" タスクをクリア
控制器/api/tag_controller.rb

Rails.application.routes.draw do

~~~~~~~~~~omit~~~~~~~~~~~

  namespace :api, format: 'json' do
    resources :tags, only: [:index, :destroy]
    post 'tags' => 'tags#create'
    post 'task/create' => 'tags#create_task'
    post 'task/clear' => 'tags#clear_tasks'
  end
end

class Api::TagsController < ApplicationController
  protect_from_forgery
  skip_before_action :verify_authenticity_token

  def index
    @tag = Tag.new
    @tags = @tag.process
    @tasks = Task.all
  end

  def create
    @tag = Tag.new(tag_params)
    begin
      @tag.save!
    rescue ActiveRecord::RecordInvalid => exception
      puts exception
    end
  end
~~~~~~~~~~omit~~~~~~~~~~~
private

  def tag_params
    # <ActionController::Parameters {"title"=>"param確認テスト", "status"=>0} permitted: true>
    params.require(:tag).permit("title", "status")
  end
~~~~~~~~~~omit~~~~~~~~~~~
end
class Tag < ApplicationRecord
  has_many :tag_task_connections, dependent: :destroy
  validates :title, :status, presence: true

  def process
    tags = Tag.all
    tasks = Task.all
    tags_hash = []
    tags.each do |tag|
      tag_hash = tag.attributes
      tag_hash["tasks"] = []
      tag.tag_task_connections.each do |connection|
        task = tasks.find(connection.task_id).attributes
        task["limit"] = (task["deadline"] - Date.today).to_i
        task["checked"] = false
        tag_hash["tasks"] << task
      end
      tags_hash << tag_hash
    end
    return tags_hash
  end
end
※从此处编辑添加

      addTag: function(){
~~~~~~~~~~omit~~~~~~~~~~~
        axios.post('/api/tags', newTag)
          .then((res) => {
            console.log(res) // here
            console.log('just created a tag')
            this.submitting = false;
            this.showNewTagForm = false;
            console.log(this.tags)
            // this.tags.push('something');
            this.newTagTitle = '';
            newTag.tag = {};
~~~~~~~~~~omit~~~~~~~~~~~
我更改了此代码,但发生了相同的错误

在index_vue.js中

this.tags.push(newTag)

this.tags.push('something')

※从此处编辑添加

      addTag: function(){
~~~~~~~~~~omit~~~~~~~~~~~
        axios.post('/api/tags', newTag)
          .then((res) => {
            console.log(res) // here
            console.log('just created a tag')
            this.submitting = false;
            this.showNewTagForm = false;
            console.log(this.tags)
            // this.tags.push('something');
            this.newTagTitle = '';
            newTag.tag = {};
~~~~~~~~~~omit~~~~~~~~~~~
这样做时,没有错误。推()是错的吗

this.tags.push('something')

→<代码>控制台.log(this.tags)
//this.tags.push('something')

※从此处编辑添加

      addTag: function(){
~~~~~~~~~~omit~~~~~~~~~~~
        axios.post('/api/tags', newTag)
          .then((res) => {
            console.log(res) // here
            console.log('just created a tag')
            this.submitting = false;
            this.showNewTagForm = false;
            console.log(this.tags)
            // this.tags.push('something');
            this.newTagTitle = '';
            newTag.tag = {};
~~~~~~~~~~omit~~~~~~~~~~~
→axios post的console.log响应结果

/api/tags

new Vue ({
    el: '#tags',
    methods: {
~~~~~~~~~~omit~~~~~~~~~~~
      addTag: function(){
        this.submitting = true;
        const newTag = {
          tag: {
            title: this.newTagTitle,
            status: 0,
            tasks: []
          }
        }
        axios.post('/api/tags', newTag)
          .then((res) => {
            console.log('just created a tag')
            this.tags.push(newTag);  //error occurring here
            this.newTagTitle = '';
            this.submitting = false;
            this.showNewTagForm = false;
          }).catch(error => {
            console.log(error);
          });
      },
      addTask: function(tagId, i) { // added by edit
        const newTask = {
          task: {
            text: this.newTaskTextItems[i].text,
            deadline: this.newTaskDeadlineItems[i].deadline,
            priority: this.newTaskPriorityItems[i].selected
          },
          tag_task_connection: {
            tag_id: tagId
          }
        }
        axios.post('/api/task/create', newTask)
          .then(() => {
            console.log('just created a task')
            newTask.task.limit = Math.ceil((parseDate(this.newTaskDeadlineItems[i].deadline).getTime() - new Date().getTime())/(1000*60*60*24));
            this.tags[i].tasks.push(newTask.task);
            this.newTaskTextItems[i].text = '',
            this.newTaskDeadlineItems[i].deadline = '',
            this.newTaskPriorityItems[i].selected = '',
            newTask.tasks = '',
            newTask.tag_task_connection = ''
          }).catch(error => {
            console.log(error);
        });
      }
~~~~~~~~~~omit~~~~~~~~~~~
    },
    mounted: function () {
      axios.get('/api/tags')
      .then( res => {
        this.tags = res.data.tags,
        this.newTaskTextItems = res.data.newTaskTextItems,
        this.newTaskDeadlineItems = res.data.newTaskDeadlineItems,
        this.newTaskPriorityItems = res.data.newTaskPriorityItems,
        this.checkedItems = res.data.checkedItems
      })
    },
    data: {
      tags: [],
      options: [
        { name: "低", id: 1 },
        { name: "中", id: 2 },
        { name: "高", id: 3 }
      ],
      showNewTagForm: false,
      showStatusFrom: false,
      changeStatusTag: 0,
      deleteConf: false,
      deleteTarget: 0,
      helloWorld: false,
      firstModal: true,
      newTagTitle: '',
      loading: false,
      submitting: false,
      newTaskTextItems: '',
      newTaskDeadlineItems: '',
      newTaskPriorityItems: ''
    }
~~~~~~~~~~omit~~~~~~~~~~~
})
10:43:20 web.1     | Started POST "/api/tags" for ::1 at 2020-09-11 10:43:20 +0900
10:43:20 web.1     | Processing by Api::TagsController#create as JSON
10:43:20 web.1     |   Parameters: {"tag"=>{"title"=>"create_tag_test7", "status"=>0, "tasks"=>[]}}
10:43:20 web.1     | Unpermitted parameter: :tasks
10:43:20 web.1     |    (0.1ms)  begin transaction
10:43:20 web.1     |   ↳ app/controllers/api/tags_controller.rb:14:in `create'
10:43:20 web.1     |   Tag Create (0.9ms)  INSERT INTO "tags" ("title", "status", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["title", "create_tag_test7"], ["status", 0], ["created_at", "2020-09-11 01:43:20.356248"], ["updated_at", "2020-09-11 01:43:20.356248"]]
10:43:20 web.1     |   ↳ app/controllers/api/tags_controller.rb:14:in `create'
10:43:20 web.1     |    (7.3ms)  commit transaction
10:43:20 web.1     |   ↳ app/controllers/api/tags_controller.rb:14:in `create'
10:43:20 web.1     | No template found for Api::TagsController#create, rendering head :no_content
10:43:20 web.1     | Completed 204 No Content in 13ms (ActiveRecord: 8.2ms | Allocations: 2708)
※axios.get正在获取此信息

{"tags":
[{"id":1,
"title":"雑務",
"status":9,
"created_at":"2020-09-05T02:46:06.031Z",
"updated_at":"2020-09-05T02:46:06.031Z",
"tasks":
[{"id":5,
"text":"家賃振り込み",
"deadline":"2020-09-03",
"priority":2,
"created_at":"2020-09-05T02:46:06.082Z",
"updated_at":"2020-09-05T02:46:06.082Z",
"limit":-8,
"checked":false},
{"id":38,
"text":"タスク作成テスト",
"deadline":"2020-09-10",
"priority":2,
"created_at":"2020-09-10T11:03:46.235Z",
"updated_at":"2020-09-10T11:03:46.235Z",
"limit":-1,
"checked":false}]},
{"id":23,
"title":"タグ削除テスト",
"status":0,
"created_at":"2020-09-10T09:13:03.977Z",
"updated_at":"2020-09-10T09:13:03.977Z",
"tasks":[]},
{"id":24,
"title":"タグ削除テスト2",
"status":0,
"created_at":"2020-09-10T09:15:01.551Z",
"updated_at":"2020-09-10T09:15:01.551Z",
"tasks":[]},
{"id":38,
"title":"create_tag_test",
"status":0,
"created_at":"2020-09-10T12:08:12.051Z",
"updated_at":"2020-09-10T12:08:12.051Z",
"tasks":[]},{"id":39,"title":"create_tag_test2","status":0,"created_at":"2020-09-10T12:08:44.929Z","updated_at":"2020-09-10T12:08:44.929Z","tasks":[]},
{"id":40,"title":"create_tag_test3","status":0,"created_at":"2020-09-10T12:10:42.491Z","updated_at":"2020-09-10T12:10:42.491Z","tasks":[]}],
"newTaskTextItems":[{"text":""},{"text":""},{"text":""},{"text":""},{"text":""},{"text":""},{"text":""},{"text":""},{"text":""},{"text":""},{"text":""},{"text":""},{"text":""},{"text":""},{"text":""},{"text":""},{"text":""},{"text":""},{"text":""}],
"newTaskDeadlineItems":[{"deadline":""},{"deadline":""},{"deadline":""},{"deadline":""},{"deadline":""},{"deadline":""},{"deadline":""},{"deadline":""},{"deadline":""},{"deadline":""},{"deadline":""},{"deadline":""},{"deadline":""},{"deadline":""},{"deadline":""},{"deadline":""},{"deadline":""},{"deadline":""},{"deadline":""}],
"newTaskPriorityItems":[{"selected":false},{"selected":false},{"selected":false},{"selected":false},{"selected":false},{"selected":false},{"selected":false},{"selected":false},{"selected":false},{"selected":false},{"selected":false},{"selected":false},{"selected":false},{"selected":false},{"selected":false},{"selected":false},{"selected":false},{"selected":false},{"selected":false}],
"checkedItems":[{"checked":false},{"checked":false}]}
服务器说

new Vue ({
    el: '#tags',
    methods: {
~~~~~~~~~~omit~~~~~~~~~~~
      addTag: function(){
        this.submitting = true;
        const newTag = {
          tag: {
            title: this.newTagTitle,
            status: 0,
            tasks: []
          }
        }
        axios.post('/api/tags', newTag)
          .then((res) => {
            console.log('just created a tag')
            this.tags.push(newTag);  //error occurring here
            this.newTagTitle = '';
            this.submitting = false;
            this.showNewTagForm = false;
          }).catch(error => {
            console.log(error);
          });
      },
      addTask: function(tagId, i) { // added by edit
        const newTask = {
          task: {
            text: this.newTaskTextItems[i].text,
            deadline: this.newTaskDeadlineItems[i].deadline,
            priority: this.newTaskPriorityItems[i].selected
          },
          tag_task_connection: {
            tag_id: tagId
          }
        }
        axios.post('/api/task/create', newTask)
          .then(() => {
            console.log('just created a task')
            newTask.task.limit = Math.ceil((parseDate(this.newTaskDeadlineItems[i].deadline).getTime() - new Date().getTime())/(1000*60*60*24));
            this.tags[i].tasks.push(newTask.task);
            this.newTaskTextItems[i].text = '',
            this.newTaskDeadlineItems[i].deadline = '',
            this.newTaskPriorityItems[i].selected = '',
            newTask.tasks = '',
            newTask.tag_task_connection = ''
          }).catch(error => {
            console.log(error);
        });
      }
~~~~~~~~~~omit~~~~~~~~~~~
    },
    mounted: function () {
      axios.get('/api/tags')
      .then( res => {
        this.tags = res.data.tags,
        this.newTaskTextItems = res.data.newTaskTextItems,
        this.newTaskDeadlineItems = res.data.newTaskDeadlineItems,
        this.newTaskPriorityItems = res.data.newTaskPriorityItems,
        this.checkedItems = res.data.checkedItems
      })
    },
    data: {
      tags: [],
      options: [
        { name: "低", id: 1 },
        { name: "中", id: 2 },
        { name: "高", id: 3 }
      ],
      showNewTagForm: false,
      showStatusFrom: false,
      changeStatusTag: 0,
      deleteConf: false,
      deleteTarget: 0,
      helloWorld: false,
      firstModal: true,
      newTagTitle: '',
      loading: false,
      submitting: false,
      newTaskTextItems: '',
      newTaskDeadlineItems: '',
      newTaskPriorityItems: ''
    }
~~~~~~~~~~omit~~~~~~~~~~~
})
10:43:20 web.1     | Started POST "/api/tags" for ::1 at 2020-09-11 10:43:20 +0900
10:43:20 web.1     | Processing by Api::TagsController#create as JSON
10:43:20 web.1     |   Parameters: {"tag"=>{"title"=>"create_tag_test7", "status"=>0, "tasks"=>[]}}
10:43:20 web.1     | Unpermitted parameter: :tasks
10:43:20 web.1     |    (0.1ms)  begin transaction
10:43:20 web.1     |   ↳ app/controllers/api/tags_controller.rb:14:in `create'
10:43:20 web.1     |   Tag Create (0.9ms)  INSERT INTO "tags" ("title", "status", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["title", "create_tag_test7"], ["status", 0], ["created_at", "2020-09-11 01:43:20.356248"], ["updated_at", "2020-09-11 01:43:20.356248"]]
10:43:20 web.1     |   ↳ app/controllers/api/tags_controller.rb:14:in `create'
10:43:20 web.1     |    (7.3ms)  commit transaction
10:43:20 web.1     |   ↳ app/controllers/api/tags_controller.rb:14:in `create'
10:43:20 web.1     | No template found for Api::TagsController#create, rendering head :no_content
10:43:20 web.1     | Completed 204 No Content in 13ms (ActiveRecord: 8.2ms | Allocations: 2708)

无论您在何处声明文本,请尝试:

 text: this.newTaskTextItems[i] ?  this.newTaskTextItems[i].text : ' ';
这样你就不会有任何错误了。并尝试console.log(this.newTaskTextItems,this.newTaskTextItems[i],i),可能其中一些是未定义的,但一些是正常的

这是我修复的

addTag: function(){
  this.submitting = true;
  const newTag = {
    tag: {
      title: this.newTagTitle,
      status: 1,
      tasks: [],
      errors: {
        text: '',
        deadline: '',
        priority: ''
      }
    }
  }
  axios.post('/api/tags', newTag)
    .then(() => {
      console.log('just created a tag')
      this.submitting = false;
      this.showNewTagForm = false;
      this.newTagTitle = '';
      if (this.errors != '') {
        this.errors = ''
      }
      var newTaskTextItem = {text: ''};
      var newTaskDeadlineItem = {deadline: ''};
      var newTaskPriorityItem = {selected: 0};
      this.newTaskTextItems.push(newTaskTextItem); //I got the error, because I hadn't been doing this.
      this.newTaskDeadlineItems.push(newTaskDeadlineItem);
      this.newTaskPriorityItems.push(newTaskPriorityItem);
      this.tags.push(newTag.tag);
    }).catch(error => {
      if (error.response.data && error.response.data.errors) {
        this.errors = error.response.data.errors;
      }
      this.submitting = false;
      this.showNewTagForm = false;
    });
},

您应该发布您的后端响应,以帮助我们了解您在模板中将
newTaskTextItems
作为数组引用,但在
数据中将其初始化为字符串的问题。Charlie I添加了后端代码。如果您需要更多,请告诉我。@MichalLevý我在方法中添加了代码。在
addTask
方法中初始化
newTaskTextItems
,但它不能解决问题。@YoheiYokota我们不关心您的后端代码。我们只关心你从后台得到的回复,我明白了!推送的标记正在调用
newTaskTextItems[i].text
。你给了我一个暗示。非常感谢。