block by timelyportfolio 8306c14e03888a00f827aec148a0fd2b

vue with shiny sendCustomMessage

Updates from R for Vue

This example is intended to be an ultra-simple illustration of how we might update some state on the JavaScript side from R/Shiny. Please do not consider this “best practice”. I will try to explain with comments in the code.

For a more advanced example, see vue d2b sunburst updated with Shiny

Code with Comments

library(shiny)

ui <- tagList(
  # set up a div that will show state
  tags$div(id = "app", "{{data}}"),
  tags$script("
// careful here in a real application
//  set up a global/window store object to hold state
//  will be a simple object
var store = {data:{}};

// add a very simple function that will update our store object
//   with the x data provided
Shiny.addCustomMessageHandler(
  'updateStore',
  function(x) {
    // mutate store data to equal the x argument
    store.data = x;
    console.log('changed to ' + x);
  }
);

// super simple Vue app that watches our store object
var app = new Vue({
  el: '#app',
  data: store // probably better as function(){ return store; }
});
"
  ),
  # add Vue dependency
  vueR::html_dependency_vue(offline = FALSE)
)

server <- function(input,output,session) {
  observe({
    # every 1 second invalidate our session to trigger update
    invalidateLater(1000, session)
    # send a message to update store with a random value
    session$sendCustomMessage(
      type = "updateStore",
      message = runif(1)
    )
  })
}

shinyApp(ui, server)