top of page
  • 執筆者の写真T sakurako

VueでWEBアプリ(13)

前回書いたように、フォームの実装を進めています。

まずは、見た目と大体のコードの形をこちらを参考に作成しました。



その時詰まってしまい、解決したのでここに残しておこうと思います。


 

Property or method "submit" is not defined on the instance but referenced during render.


先の記事を参考にフォーム画面を作成したのですが、画面表示時点で以下のエラーが出ていました。


[Vue warn]: Property or method "submit" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.

送信ボタンを押しても想定通りの動きをせず、というかsubmitの処理を通っていない状態でした。


その時のスクリプトが以下です。


export default {
  data () {
    return {
        success: false,
        title: '',
        titleRules: [
          v => !!v || 'タイトルは必須項目です。',
          v => (v && v.length <= 10) || 'タイトルは10文字以内です。'
        ],
        author: '',
        authorRules: [
          v => !!v || '投稿者は必須項目です。',
          v => (v && v.length <= 10) || '投稿者は10文字以内です。'
        ],
        post_date: '',
        post_dateRules: [
          v => !!v || '日付は必須項目です。',
          v => (v && v.length <= 10) || '日付は10文字以内です。'
        ],
        content: '',
        contentRules: [
          v => !!v || '本文は必須項目です。',
          v => (v && v.length <= 10) || '本文は10文字以内です。'
        ],
      methods: {
        submit() {
          if (this.$refs.test_form.validate()) {
          // すべてのバリデーションが通過したときのみ
          // if文の中に入る
          this.success = true;
        } else {
          this.success = false;
        }         }  
      },
      components: {
        AppBackgroundHolder,
      },
    }
  }
}




なんでダメだったのか


まあ単純なミスでして、data(){}の中にmethodsやconmpnetsが入っていたせいでした。

これらは並列して書かれるべきものなのですが、なぜかdataの中のものだと思い込んでいました…。ほかの正しく書かれているページのコンポーネントと見比べたうえで

気がづかず…。


しかもこのフォーム画面を作成したとき、下の画像のようにほかの画面と同じく背景画像とページタイトルが表示されるはずがうまくいかなかったりしたのですが、これもcomponentsが正しい場所になかったせいでした。




コピペでばかりで構造をちゃんと見ていませんでした。反省。

以下のように修正し、想定通りの動きになることを確認できました。


export default {
  components: {
    AppBackgroundHolder,
  },

  data () {
    return {
      title_f:'Form',
      title: '',
      author: '',
      post_date: '',
      content: '',
      titleRules: [
        v => !!v || 'タイトルは必須項目です。',
        v => (v && v.length <= 10) || 'タイトルは10文字以内です。'
      ],
      authorRules: [
        v => !!v || '投稿者は必須項目です。',
        v => (v && v.length <= 10) || '投稿者は10文字以内です。'
      ],
      post_dateRules: [
        v => !!v || '日付は必須項目です。',
        v => (v && v.length <= 10) || '日付は10文字以内です。'
      ],
      contentRules: [
        v => !!v || '本文は必須項目です。',
        v => (v && v.length <= 10) || '本文は10文字以内です。'
      ],
    }
  },
  methods: {
    submit() {
      if (this.$refs.formref.validate()) {
        // すべてのバリデーションが通過したときのみ
        // if文の中に入る
        this.success = true;
      } else {
        this.success = false;
      }        
    }
  } 
}

 

この『VueでWEBアプリ』シリーズのコードをgithubで公開しています。参考までに。

記事: Blog2_Post
bottom of page